Search code examples
c++recursion

Reverse a string using no variables while using recursion in c++


How can you reverse a string using recursion following the constraints mentioned in the function

string reverse_recurse(string forward) { // recursive
// Constraints: No loops allowed; no static local or global variables.
// Your new code goes here...
return ""; 
}

Solution

  • Here is a quick implementation of the second approach described in Robᵩ's answer. Basically, return the last element of the string concatenated with the reverse of the other elements.

    #include <iostream>
    #include <string>
    
    std::string reverse_string(std::string a_string) {
        return
          a_string.length() > 0 ?
            a_string.back()
              + reverse_string(a_string.substr(0, a_string.length() - 1)) :
            std::string();
    }
    
    int main() {
        std::string a_string = "live on time , emit no evil";
    
        std::cout << a_string << std::endl;
        std::cout << reverse_string(a_string) << std::endl;
    
        return 0;
    }