Search code examples
c++stringrecursionreversefunction-definition

Recursive function that reverses substring within a string


I am working on a lab assignment where the user inputs a string and a starting and stopping point for a substring within the string to be reversed. For example, if a user inputs the string "go bobcats", and the numbers 3 (for starting index) and 7 (for ending index), the output should be "go acbobts". I was able to write a recursive function that reverses an entire string ("go bobcats" becomes "stacbob og"), but I am having trouble with the substring aspect.

code for full string reverse:

void reversing(string s, int start, int end){
    if(s.size() == 0){return;}
    else{
        reversing(s.substr(1), start + 1, end);
        cout << s[0];
    }
}

For the starting and ending index for this I just entered 0 and 9 because that would be the full length of the string.

How can I adjust the function so that it only reverses the string starting and ending at the indexes the user inputs? Also, with my current function I have to use an endl in the main to make a new line at the end of the output of the string. Is there a way I can do this inside the function? If I put an endl after cout << s[0]; it puts in a new line after each iteration making the output vertical:

s

t

a

c

b

o

b

o

g

Implementation in main:

string s;
    int start, end;
    cout << "Enter a string: ";
    while(cin.peek() == '\n' || cin.peek() == '\r'){
        cin.ignore();
    }
    getline(cin,s);
    cout << "Now enter two numbers that are within the bounds of the string. ";
    cin >> start >> end;
    cout << "This is how your words look now:\n";
    reversing(s,start,end);
    cout << endl;

Solution

  • A function to reverse the string can swap the elements at both ends of the range and decrease the range by one on both sides.

    void reversing(string& s, int start, int end) {
        if (start >= end)
            return;
        swap(s[start], s[end]);
        reversing(s, start + 1, end - 1);
    }
    

    And then inside main():

    // ...
    cout << "This is how your words look now:\n";
    reversing(s, start, end);
    cout << s << endl;