A string can be reversed recursively by processing characters from left to right and printing them while the recursive calls return.
- The recursive function reaches the end of the string before printing any character.
- Characters are printed in reverse order as the function calls return.
Example
Input: "Geeks for Geeks"
Output: "skeeG rof skeeG"Input: "Hello World"
Output: "dlroW olleH"
Approaches to Print the Reverse of a String Using Recursion
There are two approaches to print the reverse of a string using recursion:
1. Using substr()
The idea is to recursively call the function with the string excluding its first character. Once the end of the string is reached, each recursive call prints its first character while returning.
#include <bits/stdc++.h>
using namespace std;
/* Function to print reverse of the passed string */
void reverse(string str)
{
if(str.size() == 0)
{
return;
}
reverse(str.substr(1));
cout << str[0];
}
/* Driver program to test above function */
int main()
{
string a = "Geeks for Geeks";
reverse(a);
return 0;
}
// This is code is contributed by rathbhupendra
Output
skeeG rof skeeG
Explanation: Recursive function (reverse) takes string pointer (str) as input and calls itself with next location to passed pointer (str+1). Recursion continues this way when the pointer reaches '\0', all functions accumulated in stack print char at passed location (str) and return one by one.
2. Using Index-Based Recursion
A more efficient approach is to avoid creating new substrings. The function passes the string along with the current index and prints the character while recursion unwinds.
#include <iostream>
#include <string>
using namespace std;
void reverseString(const string& str, int index) {
if (index == str.size())
return;
reverseString(str, index + 1);
cout << str[index];
}
int main() {
string str = "Geeks for Geeks";
reverseString(str, 0);
return 0;
}
Output
skeeG rof skeeG
Explanation: The function moves through the string using index. After reaching the end, it returns through the recursive calls and prints each stored index in reverse order.