-4

I'm having trouble figuring out to how to reverse a string recursively using only one reference parameter like the signature below.

void reverse(string &s)
{
if (s.size() == 0) //this doesn't work because the size is never changing
    return;

string new_word = s.substr(1) + s.at(0);
reverse(new_word);
}

I managed to do it just fine returning a new string but for some reason I'm stumped on this one.

Any suggestions? Thanks.

  • 1
    Post the rest of your code – olevegard Aug 25 '13 at 21:58
  • Why are you constraining yourself in this way? – David Heffernan Aug 25 '13 at 21:59
  • 2
    @DavidHeffernan To ensure that the resulting code be both unreadable and excessively inefficient? – James Kanze Aug 25 '13 at 22:04
  • I edited it and added my code. My problem is that I have no idea how to write the base case for this. The size of the parameter is never going to change. – user2716299 Aug 25 '13 at 22:07
  • I'm virtually positive that this "test" is supposed to be for a function that returns the string. Otherwise what's supposed to change between calls to the recursive function? Something like this is easy to convert to c++: http://stackoverflow.com/questions/9723912/reversing-a-string-recursion-java – dcaswell Aug 25 '13 at 22:09

2 Answers2

2

Here is a recursive version working :

void reverse( string& word )
{
    if ( word.size() <= 1 ) return;

    // Get the string without the first and the last char
    string temp = word.substr( 1, word.size() - 2 );
    // Reverse it
    reverse( temp );

    // Recompose the string
    word = word.substr( word.size() - 1 ) + temp + word[0];
}

But I really suggest you to stay on an iterative version :

// No need to explain, pretty clear
void reverse(string& word)  
{
    unsigned int end = word.size() - 1;
    for ( unsigned int i = 0; i < end; i++, end-- )
    {
        char c = word[end];
        word[end] = word[i];
        word[i] = c;
    }
}

Example with both.


And like suggested syam use std::reverse :

std::reverse(str.begin(), str.end());
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62
1

Since you already have a version that reverses the string but returns it, you simply need

void reverse(string& word)  
{
    word = version_that_returns_reversed_string(word);
}
a.lasram
  • 4,371
  • 1
  • 16
  • 24