Search code examples
c++recursionreverse

Recursive Function to reverse a string C++


I have previously found this code in doing a recursion on string reversing but I couldn't understand how the code work, could I possibly get some explanation? thank you!

std::string reverse(std::string str) {
    if(str.length()==0)
        return "";  
    return reverse(str.substr(1)) + str[0];
}

Solution

  • You can find the explanation in the following diagram, I suspect.

    enter image description here