Reverse a string in C/C++


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

Example

#include<stdio.h>
#include<string.h>

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

   printf("\nEnter 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("\nReverse string is : %s", s);
   return (0);
}

Output

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;
   i++;
   j--;
}

Updated on: 25-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements