Possible Duplicate:
Write a recursive function that reverses the input
Recently, I've been reading the book C++ For Everyone and I've been having trouble putting together a recursive function (Confusing to think about...)
The question was: Write a recursive function string reverse(string str)
that returns the reverse of str
This is what I have so far:
string reverse(string str)
{
string word = "";
if (str.length() <= 1)
{
return str;
}
else
{
string str_copy = str;
int n = str_copy.length() - 1;
string last_letter = str_copy.substr(n, 1);
str_copy = str_copy.substr(0, n);
word += reverse(str_copy);
return last_letter;
}
return word;
}
My problems now is:
If I enter wolf
, it returns f
If I change return last_letter
to return word
, I get w
If I change to return str_copy
, I get wol