How To Reverse A String In C?

How To Reverse A String In C?

Introduction

Reversing a string is an important problem that is famous across many competitive coding problem banks. Before that, what is a string?

A string is a set of characters stored in an array, or we can also define it as an array of characters, followed by a null character. The task is to reverse the string.

For example, if you give a string as “Heyy”, the output would be “yyeH.” 

We have many methods to reverse a string, like 

 Let’s discuss some of the methods to reverse a string in C.

1. Reverse a String using the library function- strrev():

The strrev() function directly reverses the given string, and this function is present in string.h library. The code for this function is inbuilt in the library, we need to just give a string as the input to the function.

C Code:

#include <stdio.h>
#include <string.h>
int main()
{
   char s[100]; //string declaration
   printf("Enter a string:");
   gets(s); //input
   strrev(s); //reversing string
   printf("The reverse of the string: %s\n", s);
   return 0;
}

Output:

Enter a string: Hello
The reverse of the string: olleH

2. String Reverse using another String:

The idea is to transfer the string to another string in a reverse manner. All we need is the size of the string. The approach is to initialize a character array of the same size and start copying the elements of the input string from the end.

C Code:

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

   end = count - 1;
   for (begin = 0; begin < count; begin++) {
      r[begin] = s[end];
      end--;
   }

   r[begin] = '\0';

   printf("%s\n", r);

   return 0;
}

Output:

Input a string: CodingNinjas
sajniNgnidoC

3. Reverse a String using swapping in the same string:

This approach is space-efficient. Take two pointers, one at the beginning and the other at the end. Swap the characters stored in both the pointers until the start is greater than the end. This would produce an in place reversed array.

C Code:

#include <stdio.h>
#include <string.h>
void reverseStr(char str[])
{
  int n = strlen(str);

  for (int i = 0; i < n / 2; i++)
  {
    char ch = str[i];
    str[i] = str[n - i - 1];
    str[n - i - 1] = ch;
  }
}

int main()
{
  char str[1000];
  scanf("%s", str);
  reverseStr(str);
  printf("\nString After Reverse: %s", str);
  return 0;
}

Output:CodingNinjas

String After Reverse: sajniNgnidoC

In the above code, characters are swapped in the same string by using the index values.

4. Reverse a String using recursion:

As we all know, recursion is the concept where we perform an operation on a single element and the recursive function call returns the updated object.

To reverse the string:

  • Remove one character from the string. 
  • Call the recursive function.
  • Insert the removed character, such that the reverse operation holds.

C Code:

#include <stdio.h>
#include <string.h>
void reverse(char*, int, int);
int main()
{
   char a[100];
   gets(a); //read string
   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);
}

Output:

CodingNinjas
sajniNgnidoC

5. Reverse a String using Pointers:

The idea is to swap the beginning and end pointers of the string. Instead of swapping the elements, here, we will swap the pointers where the addresses of the input string are stored. 

C Code:

#include<stdio.h>
int string_length(char*);
void reverse(char*);
int main()
{
   char s[100];

   printf("Enter a string:");
   gets(s);
   reverse(s);
   printf("The reverse of the string is \"%s\".\n", s);
   return 0;
}
void reverse(char *s)
{
   int length, c;
   char *begin, *end, temp;

   length = string_length(s);
   begin  = s;
   end    = s;

   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;
}

Output:

Enter a string: CodingNinjas
The reverse of the string is “sajniNgnidoC”.

6. Reverse a String using Stack:

Stack is one of the simpler data structures that can be used for reverse operations. Since stack follows Last in First out approach. We can use this property to reverse the string.

The idea is to push all the string elements into a stack, and pop them one by one. This way the popped elements are received in reverse order.

C Code:

#include <stdio.h>  
#include <string.h>  
  
#define max 100  
int top,stack[max];  
  
void push(char x){  
  
      // Push(Inserting Element in stack) operation  
      if(top == max-1){  
          printf("stack overflow");  
      }  else {  
          stack[++top]=x;  
      }  
  
}  
  
void pop(){  
    // Pop (Removing element from stack)  
      printf("%c",stack[top--]);  
}  
  
  
int main()  
{  
   char str[]="Coding Ninjas";  
   int len = strlen(str);  
   int i;  
  
   for(i=0;i<len;i++)  
        push(str[i]);  
  
   for(i=0;i<len;i++)  
      pop();
    return 0;
} 

Output:

The reversed string is: sajniNgnidoC

Frequently Asked Questions

How do you reverse a string?

Reversing a string can be done in multiple ways. Some of them are using the strrev() function, without using the strrev() function, using pointers, recursion, and stack.

Which inbuilt function is used to reverse a string in C?

“strrev()”- is used to reverse a string in C. It is present in string.h library.

How do you reverse a string without a reverse function?

To reverse a string, there are many methods like recursion, stacks, pointers in different languages.

How do I reverse a string in STL (Standard Template Library)?

Take a copy of the original string, then use std::reverse to inplace reverse the copy. Here is the small snippet of code:
std::string str1(“original”);
std::string str2(str1);
std::reverse(str2.begin(), str2.end());

Key Takeaways

The blog described some methods like using the strrev() function and without strrev() function. And then some of the programs using recursion, pointers in C, and finally Stack using C and practicing more problems on Arrays and Strings help to crack the interviews in top product-based companies.

For more practice problems on strings, please visit the CodeStudio section. The platform has a lot of practice problems, divided among different important concepts. Moreover, you get to practice the top interview problems by the top product-based companies.

By Dharani Mandla

Exit mobile version