Reverse the String Using Recursion
For this method, we will use recursion to swap the characters.
Implementation
C
// C program to reverse string using recursion #include <stdio.h> #include <string.h> // recursive function to reverse string void reverse( char * str, int len, int i, int temp) { // if current index is less than the remaining length of // string if (i < len) { temp = str[i]; str[i] = str[len - 1]; str[len - 1] = temp; i++; len--; reverse(str, len, i, temp); } } // driver code int main() { char str[100] = "string" ; printf ( "Original String: %s\n" , str); int len = strlen (str); reverse(str, len, 0, 0); printf ( "Reversed String: %s" , str); return 0; } |
Output
Original String: string Reversed String: gnirts
Reverse String in C
Reversing a string in C is a fundamental operation that involves rearranging the characters in a string so that the last character becomes the first, the second-to-last character becomes the second, and so on.
For example,
Original String:
"string"
Reversed String:
"gnirts"
In this article, we will discuss different ways to reverse a string in C with code examples.