A string is an array of chars or bytes. The last byte is NULL. Now we need to iterate till last NULL to get the length of the string.

strrev char swap

Index of the array starts with 0. If a length of a string in len then total len+1 elements are there. Now we need to swap the char at index 0 with index len - 1. These are mirror opposite positions. Same way we need to iterate i=1,2,... till the mid of the string which is (len/2).


char *strrev (char *str)
{
  int i;
  int len = 0;
  char c;
  if (!str)
    return NULL;
  while(str[len] != '\0'){
    len++;
  }
  for(= 0; i < (len/2); i++)
  {
    c = str[i];
    str [i] = str[len - i - 1];
    str[len - i - 1] = c;
  }
  return str;
}
int main(int argc, char *argv[])
{
  char str[] ="Hello World";
  printf("Input = %s\n", str);
  strrev(str);
  printf("Output = %s\n", str);
  return 0;
}

Output:
Input = Hello World
Output = dlroW olleH

About our authors: Team EQA

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

#