Hero Vired Logo
Programs

More

Masterclasses

Home
Blogs
Reversing a String in C: Comprehensive Guide with Multiple Approaches

One can define a string as an assortment of characters followed by a null character. 

This article focuses on the different ways C language developers use to reverse a string. Learn the different ways to execute reverse strings in the C programming language. But before we begin, learn what reverse a string in C means. 

Let us first know what is Reverse A String In C.

What is Reverse a String in C

The user's input string, which was sent to your software in a specific order, gets entirely reversed when the reverse of a string algorithm is applied to it. The output, for instance, will be "olleh" if the string is "hello." 

Reversing a String in C
The palindrome can be verified using this idea. A string that doesn't change when reversed is called a palindrome. Therefore, a palindrome string will still have the same value even after being reversed. 

A user-inputted string can be reversed using various methods using a C program. In the C programming language, a given string can be reversed using the strrev function, without strrev, recursion, pointers, or another string, or displaying it in the opposite order.

How to Reverse a String in C?

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

C Program To Reverse A String Using Recursion

To reverse a string using recursion in C, you can define a recursive function that takes the string as input and returns the reversed string. Here's a C program to achieve this:

#include
#include
int main(void)
{
char mystrg[60];
int leng, g;
// Printing the program name and what the program will do
printf("Program in C for reversing a given string n ");
printf("Please insert the string you want to reverse: ");
    // fetch the input string from the user
scanf( "%s", mystrg );
// This will find the length of your string with the help of strlen() function of the string.h header file
leng = strlen(mystrg);
// iterate through each and every character of the string for printing it backward or reverse direction
for(g = leng - 1; g >= 0; g--) {
  printf("%c", mystrg[g]);
}
return 0;
}

Output

Program in C for reversing a given string
Please insert the string you want to reverse: w3schools 
sloohcs32w
……………
Process exited after 7.484 seconds with return value 0
Press any key to continue… 

Also read about: What is Arrays in C, and C++ and Advantages and Disadvantages of Arrays in C, C++ and Java

Reverse A String Using A While Loop

To reverse a string in C using a while loop, you can iterate through the string from both ends and swap the characters until you reach the middle of the string.

Check this example using a while loop in the C programming language to output the reverse of a string. 

#include   
#include   
int main()  
{  
char str1[50], temp; // declare and initialize the size of string array.  
int i = 0, j =0;  
printf (" Enter a string to be reversed: ");  
scanf( "%s", str1);  
j = strlen (str1) - 1;  // get the length of the string  
// use while loop to define the condition  
while ( i < j)   
{  
// use temp variable to store the characters of str1  
temp = str1[j];  
str1[j] = str1[i];  
str1[i] = temp;  
i++; // i incremented by 1  
j--; // j is decremented by 1  
}  
printf (" The reversed of the string: %s", str1);  
return 0;  
}  

Output

Enter a string to be reversed: JAVATPOINT
The reversed of the string: TNIOPTAVAJ

Reverse A String Using For Loop

A for-loop method is another way we can reverse a string in C. To use this method, we need two pointers—one at the beginning of the index and the other at the index. Then switch the characters, raise the starting pointer, and lower the end pointer. Simply repeat this process until the initial pointer exceeds the end pointer. 

C Code:
#include 
#include 
int main() {
  char str[100];
  printf("Enter a string:");
  // read string
  scanf("%s", str);
   
  int length = strlen(str);
  for(int start =0, end=length-1; start<end; start++,end--) {
    char temp = str[i];
    str[i] = str[j];
    str[j] = temp;       
  }
  
  printf("The reverse of the string is "%s".n", str);
  return 0;
}
 
Output:

Enter a string: hello
The reverse of the string is "olleh".

Reverse A String Using The Recursion Function

We can also reverse a string in C by recursion function. Recursion, as we are all aware, is a concept in which an operation is performed on a single element, and the recursive function call then returns the modified object. 

C Code:
#include 
#include 
void reverse(char*, int, int);
int main()
{
   char a[100];
   gets(a); //read string
   reverse(a, 0, strlen(a)-1);
   printf("%sn", 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:

HeroVired
deriVoreH

Reverse A String Using Pointers

To reverse a string using pointers in C, you can use two pointers to traverse the string from both ends and swap the characters until you reach the middle of the string. The only difference is that we are utilizing Pointers to segregate the logic from the main program, just like when using recursion to reverse a string. Here's a C program to achieve this:

#include 
#include 
// Function to reverse the string
// using pointers
void reverseString(char* str)
{
int l, i;
char *begin_ptr, *end_ptr, ch;
// Get the length of the string
l = strlen(str);
// Set the begin_ptr and end_ptr
// initially to start of string
begin_ptr = str;
end_ptr = str;
// Move the end_ptr to the last character
for (i = 0; i < l - 1; i++)
end_ptr++;
// Swap the char from start and end
// index using begin_ptr and end_ptr
for (i = 0; i < l / 2; i++) {
// swap character
ch = *end_ptr;
*end_ptr = *begin_ptr;
*begin_ptr = ch;
// update pointers positions
begin_ptr++;
end_ptr--;
}
}
// Driver code
int main()
{
// Get the string
char str[100] = "SamBali";
printf("Enter a string: %sn", str);
// Reverse the string
reverseString(str);
// Print the result
printf("Reverse of the string: %sn", str);
return 0;
}

Output

Enter a String: My Name Is Sam
Result: maS sI Eman Ym

Reverse A String Using Stack

The stack is one of the most basic data structures that can be utilized for to reverse a string in C. We may use this characteristic to reverse the text because the stack adheres to the Last in, First out principle. The goal is to stack the string items and pop each separately. The popped elements arrive in reverse order in this manner. 

C Code:

#include   
#include   
  
#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[]="HeroVired";  
   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: deriVoreH

Reversing a String in C

Conclusion

IWe trust that you comprehend the subject and now fully grasp the idea. Enroll in the Data Science and Analytics course by HeroVired to learn more about writing code for complicated outputs. 

Get started with HeroVired’s skill-up course to discover and learn in-demand talents on your schedule if you want to improve your skill or perhaps consider taking a new course in this area.

FAQ's

There are multiple ways to reverse a string, The most common approach is to iterate through the string from both ends and swap characters until reaching the middle. The other methods are using the strrev() function, using pointers, recursion, and stack.

In the C programming language, a given string can be reversed by leveraging the strrev function, recursion, pointers, or another string, or by showing it in the opposite order.

The string reverse approach entails flipping the order of the characters in a string so that the beginning and last characters are switched.

The strrev() function, which is available anytime in the string.h library reverses the given string. We only need to provide a string as the function's input because the function's code is already included in the library.

To reverse a string in C, you can use a simple program using strrev method () method, that iterates through the string from both ends and swaps the characters until you reach the middle of the string.

Related Blogs

Blogs from other domain

Carefully gathered content to add value to and expand your knowledge horizons

Hero Vired logo
Hero Vired is a premium LearnTech company offering industry-relevant programs in partnership with world-class institutions to create the change-makers of tomorrow. Part of the rich legacy of the Hero Group, we aim to transform the skilling landscape in India by creating programs delivered by leading industry practitioners that help professionals and students enhance their skills and employability.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Cloud for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Finance & Management

Certificate Program in Financial Analysis, Valuation and Risk Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Privacy Policy And Terms Of Use
©2023 Hero Vired. All Rights Reserved.