Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a recursive function that reverses the input string

I've been reading the book C++ For Everyone and one of the exercises said to write a function string reverse(string str) where the return value is the reverse of str.

Can somebody write some basic code and explain it to me? I've been staring at this question since yesterday and can't figure it out. The furthest I've gotten is having the function return the first letter of str (Which I still don't know how it happened)

This is as far as I got (An hour after posting this question):

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 str_copy;
    }
    return word;
}

If I enter "Wolf", it returns Wol. Somebody help me out here If I return word instead of return str_copy then I get a w If I return last_letter then I get an l

like image 688
Alex Avatar asked Apr 22 '11 22:04

Alex


2 Answers

I'll instead explain the recursive algorithm itself. Take the example "input" which should produce "tupni". You can reverse the string recursively by

  • If the string is empty or a single character, return it unchanged.
  • Otherwise,
    1. Remove the first character.
    2. Reverse the remaining string.
    3. Add the first character above to the reversed string.
    4. Return the new string.
like image 110
David Harkness Avatar answered Jan 01 '23 20:01

David Harkness


Here is my version of a recursive function that reverses the input string:

void reverse(char *s, size_t len)
{
    if ( len <= 1 || !s )
    {
        return;
    }
    std::swap(s[0], s[len-1]);// swap first and last simbols
    s++; // move pointer to the following char
    reverse(s, len-2); // shorten len of string
}
like image 39
Ann Orlova Avatar answered Jan 01 '23 19:01

Ann Orlova