简体   繁体   中英

How to reverse a string using a recursive function?

I've seen lots of posts about reversing a string with recursion, but I like to use my own style of coding to properly understand it. Anyway here is the code I have.

private static String reverse (String s){

    String rev = "";
    int index = s.length()-1;
    if(index >= 0){

        rev += s.charAt(index);
        index--;
        rev += reverse(rev);


    }
        return rev;

    }

Basically index just keeps going for every single character when index is -1 the loop stops. it reads the last possible character of the string but there is an error in this line here.

rev += rev(str)

Here is iterative method

String dog = "dog";
String rev = "";

int index = dog.length()-1;
while(index >= 0){
    rev+=dog.charAt(index);
    index--;

}

out.println(rev);

I believe when the method calls itself you reset the value of the index. Maybe a better approach would be to have an overloaded method where the original call passes in the string to process and then the remaining calls call a method where you pass in both the string you are building along with the remaining part of the that is being processed.

The recursive step doesn't contain the mutated string. You need to pass the substring of the original string. rev = reverse(s.substring(0,index));

(Posted answer on behalf of the OP) .

It's fixed now. Thank you so much, I was indexing too late and passing in negative numbers.

private static String reverse (String s) {

int index = s.length();
index--;
String rev = "";
if(index >= 0){
    rev += s.charAt(index);

    rev = rev + reverse(s.substring(0,index));
}

return rev;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM