You are here

Reverse a string in C

Reverse a string in C: This program reverses a string entered by a user. For example, if a user enters a string "reverse me" then on reversing it will be "em esrever". C program to reverse a string using strrev library function of "string.h", without using strrev, recursion and pointers.

String reverse in C

#include <stdio.h>
#include <string.h>
 
int main()
{
   char arr[100];
 
   printf("Enter a string to reverse\n");
   gets(arr);
 
   strrev(arr);
 
   printf("Reverse of entered string is \n%s\n",arr);
 
   return 0;
}

Download Reverse string program.

C reverse string program output:
Reverse string C program outputC program to reverse words in a string

Reverse string C program without using strrev

First we calculate length of the string without using strlen function and then copy its characters in reverse order (from end to beginning) to a new string using a for loop.

#include <stdio.h>
 
int main()
{
   char s[1000], r[1000];
   int begin, end, count = 0;
 
   printf("Input a string\n");
   gets(s);
 
   // Calculating string length
 
   while (s[count] != '\0')
      count++;
 
   end = count - 1;
 
   for (begin = 0; begin < count; begin++) {
      r[begin] = s[end];
      end--;
   }
 
   r[begin] = '\0';
 
   printf("%s\n", r);
 
   return 0;
}

C program to reverse a string using recursion

#include <stdio.h>
#include <string.h>
 
void reverse(char*, int, int);
 
int main()
{
   char a[100];
 
   gets(a);
 
   reverse(a, 0, strlen(a)-1);
 
   printf("%s\n",a);
 
   return 0;
}
 
void reverse(char *x, int begin, int end)
{
   char c;
 
   if (begin >= end)
      return;
 
   c          = *(x+begin);
   *(x+begin) = *(x+end);
   *(x+end)   = c;
 
   reverse(x, ++begin, --end);
}

In the recursive method, we swap characters at the beginning and the end of the string and then move towards the middle of the string. This way is inefficient due to repeated function calls but useful in practicing recursion.

C program to reverse a string using pointers

Now we will invert a string using pointers or without using the library function strrev.

#include<stdio.h>
 
int string_length(char*);
void reverse(char*);
 
main() 
{
   char string[100];
 
   printf("Enter a string\n");
   gets(string);
 
   reverse(string);
 
   printf("Reverse of entered string is \"%s\".\n", string);
 
   return 0;
}
 
void reverse(char *string) 
{
   int length, c;
   char *begin, *end, temp;
 
   length = string_length(string);
   begin  = string;
   end    = string;
 
   for (c = 0; c < length - 1; c++)
      end++;
 
   for (c = 0; c < length/2; c++)
   {        
      temp   = *end;
      *end   = *begin;
      *begin = temp;
 
      begin++;
      end--;
   }
}
 
int string_length(char *pointer)
{
   int c = 0;
 
   while( *(pointer + c) != '\0' )
      c++;
 
   return c;
}