noobkid
noobkid

Reputation: 17

string reversal via recursion in c++

i have tried my code after looking for some solutions online. There was one algorithm regarding string reversal via recursion and i tried my best to make my code according to that algorithm. unfortunately, my code only swaps the first and the last characters in the given string but not the characters second with second last and so on. any help would be appreciated here's my code:

string reverse(string s,int length,int start=0){

    if (start>=length){
        return s;
    }
    else{
        char temp=s[length];
        s[length]=s[start];
        s[start]=temp;
        reverse(s,--length,++start);
    }return s;
}

int main(void) {

    string a;cout<<"enter a string:";getline(cin,a);
    cout<<reverse(a,a.length()-1,0);
}

Upvotes: 0

Views: 99

Answers (2)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

You need to pass the string by reference, not by value in the reverse function:

string reverse(string& s,int length,int start=0){

Live Example: http://ideone.com/pJ3G9l

The reason why a reference works is that you are reversing the current string, not a temporary string.

As the comment suggested, if the desired effect is to not alter the original string, then a helper function that does the recursion would work.

string reverse_helper(string& s,int length,int start)
{
    if (start>=length)
        return s;
    else
    {
        char temp=s[length];
        s[length]=s[start];
        s[start]=temp;
        reverse_helper(s,--length,++start);
    }
    return s;
}

string reverse(string str, int length, int start=0)
{
    return reverse_helper(str, length, start);
}

Live example of helper function: http://ideone.com/RzY1Bu

Upvotes: 1

clcto
clcto

Reputation: 9648

Instead of returning s, which is a copy of the original string with the first and last characters switched, you need to return the next call to reverse():

else{
    //...
    return reverse( s, --length, ++start );
}

Upvotes: 3

Related Questions