Reverse a String in C: Reversing a string means replacing the last element in the first position and vice versa and doing it for all characters in a string. For example, the first character is swapped with the last character, the second character is swapped with the second last character and so on.
A string whose reverse string is the same as the original string is called a palindrome.
Examples:
Input string: “hello”
Reversed String: “olleh”
Input string: “Sanfoundry C Programming”
Reversed string: “gnimmargorP C yrdnuofnaS”
Write a C program to reverse a string.
There are several ways to reverse a string in C language. Let’s take a closer look at all of the methods for reversing a string in C.
- Reverse a String in C using Loops
- Reverse a String in C using Recursion
- Reversing a String in C using Functions
- Reverse a String in C using strrev Function (Inbuilt Function)
- Reverse a String in C using Pointers
- Reverse a String in C using 2D Array
- Reverse a String in C using using Recursion and Iteration
In this approach, we have one variable pointing at the first index and one at last. In each step we swap both characters, increment the first variable and decrement the second variable until the first is less than the second one.
Examples:
Input string: “hello world”
“hello world” will be reversed to “dlrow olleh”
Reversed string: “dlrow olleh”
Here is the source code of the C program to reverse a string using loops. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C program to reverse a string using loops */ #include<stdio.h> #include<string.h> int main() { char str[20]; printf("Enter String: "); gets(str); printf("Entered string is: %s\n",str); int start=0,end=strlen(str)-1; // Start variable points at the start of the string // End Variables points at the last index of the string while(start<end) { //Swapping characters at start and end char temp=str[start]; str[start]=str[end]; str[end]=temp; //Incrementing start and decrementing end start++; end--; } printf("Reversed string is: %s",str); return 0; }
1. Start the program.
2. Take a string as input.
3. Declare two variables pointing to the first and last index of the string.
4. Swap the characters at their places and increment variables pointing to first character and decrement variable pointing to last character.
5. Do it until the first variable is less than the second one.
6. Print the Reversed String.
7. End the Program.
Time Complexity: O(n)
In the above program, we are traversing the string so time complexity is O(n).
Space Complexity: O(1)
Since no auxiliary space is required, space complexity is O(1).
Here we enter the string “hello world” as input.
Enter String: hello world Entered string is: hello world Reversed string is: dlrow olleh
In Recursive Approach, we swap the character at index i with character at index (n-i-1), where n is the size of the string, until i reaches the middle of the string.
Examples:
Input string: “hello world”
“hello world” will be reversed to “dlrow olleh”
Reversed string: “dlrow olleh”
Here is the source code of the C program to reverse a string using recursion. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C program to reverse a string using recursion */ #include <stdio.h> #include<string.h> char* reverse(int start,int mid,int n, char str[20]) { // Base Condition if(start==mid) return str; char temp=str[start]; str[start]=str[n-1-start]; str[n-1-start]=temp; // Recursive Calls return reverse(start+1,mid,n,str); } int main() { char str[20]; printf("Enter String: "); gets(str); printf("Entered string is: %s\n",str); int start=0,end=strlen(str)-1; int mid=(start + end)/2; printf("Reversed string is: %s",reverse(0,mid,end+1,str)); return 0; }
1. Start the program.
2. Take a string as input.
3. Declare a function to reverse a string which recursively calls itself to reverse the string with base condition to stop when half of the string is traversed.
4. Call the function for further reversal of characters.
5. Print the Reversed String.
6. End the Program.
Time Complexity: O(n)
In the above program, we are traversing the string so time complexity is O(n).
Space Complexity: O(1)
Since no auxiliary space is required, space complexity is O(1).
Here we enter the string “hello world” as input.
Enter String: hello world Entered string is: hello world Reversed string is: dlrow olleh
In this approach, we declare a function in which we swap strings with an approach similar to naive approach and then simply return that string.
Examples:
Input string: “Sanfoundry C Programming”
“Sanfoundry C Programming” will be reversed to “gnimmargorP C yrdnuofnaS”
Reversed string: “gnimmargorP C yrdnuofnaS”
Here is the source code of the C program to reverse a string using functions. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C program to reverse a string using functions */ #include <stdio.h> #include<string.h> char* reverse(int start,int end, char str[20]) { // Start variable points at the start of the string // End Variables points at the last index of the string while(start<end) { //Swapping characters at start and end char temp=str[start]; str[start]=str[end]; str[end]=temp; //Incrementing start and decrementing end start++; end--; } //Returning reversed string return str; } int main() { char str[20]; printf("Enter String: "); gets(str); printf("Entered string is: %s\n",str); int start=0,end=strlen(str)-1; printf("Reversed string is: %s",reverse(0,end,str)); return 0; }
1. Start the program.
2. Take a string as input.
3. Declare a function to reverse a string which swaps the character with their corresponding characters. (Ideology is the same as naive approach)
4. Call the function.
5. Print the Reversed String.
6. End the Program.
Time Complexity: O(n)
In the above program, we are traversing the string so time complexity is O(n).
Space Complexity: O(1)
Since no auxiliary space is required, space complexity is O(1).
Here we enter the string “Sanfoundry C Programming” as input.
Enter String: hello world Entered string is: Sanfoundry C Programming Reversed string is: gnimmargorP C yrdnuofnaS
In this approach, we declare a string and pass it call strrev(), an inbuilt function which takes a string and then print the reversed string (strrev is a non standard function, so won’t work on modern compilers).
Here is the source code of the C program to reverse a string using strrev Function. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C program to reverse a string using strrev Function */ #include<stdio.h> #include <string.h> int main() { char str[20]="I love Sanfoundry"; printf("String is: %s",str); printf("\nReversed String is: %s",strrev(str)); return 0; }
1. Start the program.
2. Declare a String.
3. Call the strrev() function and print the reversed string.
4. End the program
Time Complexity: O(n)
In the above program, we are traversing the string so time complexity is O(n).
Space Complexity: O(1)
Since no auxiliary space is required, space complexity is O(1).
In this case, we enter the string “I love Sanfoundry” as input.
String is: I love Sanfoundry Reversed String is: yrdnuofnaS evol I
In this approach, we reverse the string using the pointers. First pointer points at the start of the string and second at the last and in each iteration we swap the two characters and increment and decrement respectively.
Here is the source code of the C program to reverse a string using pointers. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C program to reverse a string using pointers */ #include<stdio.h> #include<string.h> char *rev_string(char *str) { //start points to start, end points to last and temp is for swapping two characters char *start,*end,temp; start=str; end=str; int len=strlen(str); //pointing end to last character for(int i=0;i<len-1;i++) end++; for(int i=0;i<len/2;i++) { //Swapping characters at start and end places temp=*start; *start=*end; *end=temp; //Incrementing start and decrementing end character start++; end--; } return str; } int main() { char str[50]; printf("Enter String: "); gets(str); char *rev=rev_string(str); printf("Reversed String is: %s",rev); return 0; }
1. Start the program.
2. Take a string as input.
3. Declare a function to reverse a string which takes a string as parameter.
4. In the function:
- Declare two pointers start and end.
- Initially Start and end both points at the first character of string.
- Iterate end to end of the string.
- Now swap characters at start and end until start is less than end.
- Return the reversed string.
5. Print the Reversed String.
6. End the Program.
Time Complexity: O(n)
In the above program, we are traversing the string so time complexity is O(n).
Space Complexity: O(1)
Since no auxiliary space is required, space complexity is O(1).
Here we enter the string “hello world” as input.
Enter String: I love Sanfoundry Reversed String is: yrdnuofnaS evol I
In this approach, we will reverse every word of given string using 2D array.
Here is source code of the C Program to reverse every word of given string. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Reverse every Word of given String using 2D Array
*/
#include <stdio.h>
#include <string.h>
void main()
{
int i, j = 0, k = 0, x, len;
char str[100], str1[10][20], temp;
printf("Enter the string: ");
scanf("%[^\n]s", str);
/* reads into 2d character array */
for (i = 0;str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
str1[k][j]='\0';
k++;
j=0;
}
else
{
str1[k][j]=str[i];
j++;
}
}
str1[k][j] = '\0';
/* reverses each word of a given string */
for (i = 0;i <= k;i++)
{
len = strlen(str1[i]);
for (j = 0, x = len - 1;j < x;j++,x--)
{
temp = str1[i][j];
str1[i][j] = str1[i][x];
str1[i][x] = temp;
}
}
for (i = 0;i <= k;i++)
{
printf("%s ", str1[i]);
}
}
1. Take a string as input and store it in the array str[].
2. Using for loop store each word of the input string into the 2-D array str1[][].
3. In the 2-D array str1[][] reverse each word of the string at each row of the array.
4. Print the 2-D array as output.
Here we enter the string “C Programming Class” as input.
Enter the string: C Programming Class C gnimmargorP ssalC
In this approach, we will reverse using both recursion and iteration.
Here is source code of the C Program to reverse the string using both recursion and iteration. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to Reverse the String using Both Recursion and Iteration */ #include <stdio.h> #include <string.h> /* Function Prototype */ void disp_str1_rec(char *); void main() { char str1[100], *ptr; int len1 = 0, i; char ch; printf("Enter the string:\n"); scanf("%[^\n]s", str1); ptr = str1; len1 = strlen(str1); printf("Using iteration:\n"); for (i = len1 - 1; i >= 0;i--) /* Iterative loop */ { ch = str1[i]; printf("%c", ch); } printf("Using recurssion:\n"); disp_str1_rec(ptr); } /* Code to reverse the string using Recursion */ void disp_str1_rec(char *stng) { char ch; if (*stng != '\0') { ch = *stng; stng++; disp_str1_rec(stng); printf("%c", ch); } else return; }
Enter the string: welcome to sanfoundry's c programming class Using iteration: ssalc gnimmargorp c s'yrdnuofnas ot emoclew Using recurssion: ssalc gnimmargorp c s'yrdnuofnas ot emoclewi
To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Watch Advanced C Programming Videos
- Buy C Books
- Apply for C Internship
- Practice BCA MCQs
- Buy Computer Science Books