Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

How to Reverse a String in C?

Last Updated on May 5, 2023 by Prepbytes

One major challenge that is well-known in many problem banks for competitive coding is reversing a string. First, let’s define a string.
A string may alternatively be defined as an array of characters followed by a null character. A string is a collection of characters that are kept in an array. Reversing the string is the task. There are several ways to execute reverse string in the C language. First, let’s define Reverse A String In C.

What is Reverse a String in C?

Reversing a string in the C programming language means inverting the characters’ positions such that the final character becomes the first, the next-to-last character becomes the second, and so on.
A string is said to be reversed when the characters that were previously at the end are now at the beginning, and vice versa.
The reversed string would be "setyBperP" if the initial string was "PrepBytes".
Programmers frequently need to reverse strings for a variety of reasons, including search and sorting algorithms.

Different Ways to Find the Reverse of a String in C

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

  • Reverse a String using the library function- strrev()
  • Reverse a String using another String
  • Reverse a String using swapping in the same string
  • Reverse a String using recursion
  • Reverse a String using Pointers
  • Reverse a String using Stack

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

The string.h library has the strrev() method, which immediately reverses the given string. Simply providing a string as the function’s input will execute the code that is already present in the library.

Code Implementation:

#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

Method 2: Reverse a String using another String

Its objective is to reverse the string’s transfer from one string to another. The string’s length is all that is required. The method involves initializing a character array of the same size and beginning to copy input string elements from the end.

Code Implementation:

#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: Coding Practice
ecitcarP gnidoC

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

This method is space efficient. Take two pointers place one at the start and one at the end. Change the characters stored in each pointer such that the start exceeds the end. This would result in an array that is inverted in place.

Code Implementation:

#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("String After Reverse: %s", str);
  return 0;
}

Output:

Coding Practice
String After Reverse: ecitcarP gnidoC

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

Method 4: Reverse a String using recursion

Everyone is familiar with the concept of recursion, where an action is performed on a single element, and the recursive function call returns the updated object.
Reverse a string:

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

Code Implementation:

#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:

Coding Practice
ecitcarP gnidoC

Method 5: Reverse a String using Pointers

The objective is to flip the string’s beginning and end points. Here, we’ll swap the pointers that store the input string’s addresses rather than the elements themselves.

Code Implementation:

#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: Coding Practice
The reverse of the string is "ecitcarP gnidoC".

Method 6: Reverse a String using Stack

One of the most basic data structures that may be utilized for reverse operations is the stack. Since the stack uses the Last in, First out principle. This characteristic allows us to reverse the string.
The plan is to stack all of the string components and then pop each one one at a time. The popped elements are then received in reverse order in this manner.

Code Implementation:

#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 Practice";  
   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: ecitcarP gnidoC

Conclusion
The blog discussed many techniques both with and without the strrev() function. Then, some programs that use recursion, pointers in C, and finally, Stack using C, as well as doing more array and string problems, can help you succeed in interviews with top product-based companies.

Frequently Asked Questions

Q1. How do you reverse a string?
Ans. There are various methods for reversing a string. Using a loop and starting your traversal from the last is the simple solution. The other techniques are stack, recursion, pointers, and the strrev() function.

Q2. Which inbuilt function is used to reverse a string in C?
Ans. The ability to reverse a string is not a built-in function in C. However, you have the option of creating your own function or using one from a library, such as strrev(), which is present in some C compilers like Borland, Turbo C, etc.

Q3. How do you reverse a string without a reverse function?
Ans. Without utilizing a reverse function like strrev(), you may swap the characters in a string by creating your own algorithm. The pointer, recursion, and other techniques are also available.

Q4. How to reverse a string in C simple program?
Ans. In C, there are several approaches to reverse a string. However, using the strrev() method to simply reverse it would be the simplest option. In the string.h header file, the built-in method is defined. There is no output from the function.

Q5. How do you reverse a string in a Python program?
Ans. Python has a number of methods for reversing strings, including looping, recursion, stacking, extended slices, the reversed method, list comprehension, etc. Extended slice is the simplest Python program for string reversal. Simply attaching [::-1] at the end accomplishes this.

Leave a Reply

Your email address will not be published. Required fields are marked *