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'){
10      len++;
11    }
12    for(= 0; i < (len/2); i++)
13    {
14      c = str[i];
15      str [i] = str[len - i - 1];
16      str[len - i - 1] = c;
17    }
18    return str;
19  }
20  int main(int argc, char *argv[])
21  {
22    char str[] ="Hello World";
23    printf("Input = %s\n", str);
24    strrev(str);
25    printf("Output = %s\n", str);
26    return 0;
27  }
28 
29  Output:
30  Input = Hello World
31  Output = dlroW olleH
32 

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

 Vote 0

Similar topics related to this section

variadic macro, multiple arguments in printf and scanf, strcpy and strcat source, memcpy vs memmove, strrev source, strdup, strtok, macro definition,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan