0

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);
}

2 Answers 2

3

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 );
}
Sign up to request clarification or add additional context in comments.

2 Comments

the return type is string. So how does it work with returning a string and 2 ints?
You are not returning a string and 2 ints, you are returning the value from the next call of reverse(). As you say, the return type of reverse is a string, so the type of reverse( s, --length, ++start ) is string.
1

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

1 Comment

This will also reverse the original string, so if that is not desired, it may be better to make this a helper function that is called by reverse( string, int, int )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.