Reverse a string in C/C++

C++ProgrammingServer Side Programming

Here is an example to reverse a string in C language,



int main() {
   char s[50], t;
   int i = 0, j = 0;

Enter the string to reverse :");    gets(s);    j = strlen(s) - 1;    while (i < j) {       t = s[i];       s[i] = s[j];       s[j] = t;       i++;       j--;    }    printf("
Reverse string is : %s", s);    return (0); }


Here is the output

Enter the string to reverse: Here is the input string.
Reverse string is : .gnirts tupni eht si ereH

In the above program, the actual code to reverse a string is present in main(). A char type array is declared char[50] which will store the input string given by user.

Then, we are calculating the length of string using library function strlen().

j = strlen(s) - 1;

Then, we are swapping the characters at position i and j. The variable i is incremented and j is decremented.

while (i < j) {
   t = s[i];
   s[i] = s[j];
   s[j] = t;
Updated on 25-Jun-2020 09:32:04