reversing a string using recursive
Oct 18, 2012 at 4:35am UTC
ok this is what i've written till now:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include<iostream>
#include<string>
using namespace std;
void revDisplay(const string& a);
int main()
{
string a;
cout<<"Please enter a string: " ;
getline(cin, a);
revDisplay(a);
return 0;
}
void revDisplay(const string& a)
{
size_t n = a.size();
if (n == 1)
cout << a << endl;
else
{
cout << a[n-1];
string b = a.substr(0, n-1);
revDisplay(b);
}
}
This will only output something like this:
Please enter a string: Cake
ekaC
I want it to ouput something like this:
Please enter a string: Cake
eCak
ekCa
ekaC <--- stops when first letter becomes last
i'm not really sure how to do this, any help or hints would be awesome thanks!
Oct 18, 2012 at 5:47am UTC
Try using string methods to remove the last character from the string and prepend it to the beginning. If you repeat this process size-1 times, you'll have the output you want.
Topic archived. No new replies allowed.