简体   繁体   中英

Recursively print the reverse of a String in Java

For some reason when the string length is zero, it does not come out of the while loop. Can some one help me on this?

static String str1 = "";

public static void reverse(String str) {
    while (str.length() > 0) {
        str1 = str1 + str.charAt(str.length() - 1);
        StringBuffer str_buf = new StringBuffer(str);
        str = str_buf.deleteCharAt(str.length() - 1).toString();
        reverse(str);
    }
    System.out.println("String is " + str1);
}

Replace while with if

if(str.length()>0)

Update:

The reason while fails is, after str.length() becomes 0, it hits the bottom of recursion, and control returns to the "higher" level, where str.length() is still 1. So it again calls itself.

So with while ,after it reaches 0, it will keep looping continuously between 1 and 0.

The way that you have it coded you are looping through the entire string and recursively calling the function. So for a short string "abcd" the first time through will call reverse with "abc", "ab", and "a". The reverse call to "abc" will call reverse with "ab" and "a". If you are recursively calling the function then you don't need the while loop as @sanjeev-mk suggested instead you just need the if as the exit condition.

I believe there is a more suitable code to recursively print string reverse:

public void reverseStringPrint(String inputString, int index){
    if (index < (inputString.lenght() - 1))
        reverseStringPrint(inputString, index + 1);
    System.out.print(inputString.charAt(index);
}

Run with index = 0.

In order to get the reversed string at the output (not only print it) you may do it like this:

public String reverseString(String inputString, int index){
       String restOfTheString = "";
       if (index < (inputString.lenght() - 1))
           restOfTheString = reverseStringPrint(inputString, index + 1);
       return charAt(index) + restOfTheString;
   }

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