recursive function that reverses a string!

This is what I have so far:

#include <iostream>
#include <string>

using namespace std;

string reverse(string& str);

int main()
{
string theString = "";

cout << "Enter a (backward) string: ";
getline(cin, theString);

cout << reverse(theString) << endl;

return 0;
} // end main

string reverse(string& s)
{
if (s.length() > 0)
{
return s.substr(s.length()-1);
}
else
{
return "";
}

// Implement me!!!
} // end reverse


We are learning how to use the lenght, s[], and substr methods....Anybody have any idea how to finish up the if statement so that when I enter a string backwards it reverses it? Try to keep it as basic as possible i'm really new to this. THANKS ALOT!
Last edited on

Do you have to reverse words? or just a string ?

So would: "Hello world my name is Bob" become: "Bob is name my world Hello"

or "boB si eman ym dlrow olleH"

if it's the first then perhaps you can use find_last_of " " and just print out the substrings between each space.

if the later then:
can you use the c_str() method in string class? because that will give you a char*( char[] for simplicity sake ) which you can just iterate backwards after finding the length of the std::string.
Last edited on
If i typed in abcdefg, it would become gfedcba.... I don't think I'm allowed to use that method, just those three. Is it even possible?
I'm supposed to pick off the last character of the string each time and rebuild the string from there.
ahhh ok, well if that's the way your supposed to do it I guess it works in this fashion:

we have a string: "abcdef" lets say, use substring to return the last letter by using (length()-1,length());
store this in a reverse variable and store the first part minus the last char in your original string(0,length()-1);, then do the same again, but each time concatenating the reverse string.
So first iteration you would get an 'f'
second an 'e'; and appened it to the string: f + e
then a 'd': f + e + d
... and so on..
Last edited on
Oh, ok perfect thank you so much!
Last edited on
Topic archived. No new replies allowed.