Home > DeveloperSection > Forums > What is the finest method to recursively reverse a string in Java?
Goti Bandu

Total Post:119

Points:835
Posted on    October-04-2013 9:13 AM

 Java Java 
Ratings:


 1 Reply(s)
 692  View(s)
Rate this:

I have been messing around with recursion today. Often a programming technique that is not used enough.

I set out to recursively reverse a string. Here's what I came up with:

public String reverseString(String s){
        char c = s.charAt(s.length()-1);
        if(s.length() == 1) return Character.toString(c);   
        return c + reverseString(s.substring(0,s.length()-1));
    }

 



jacob rasel
jacob rasel

Total Post:88

Points:616
Posted on    October-04-2013 9:29 AM

The finest way is not to use recursion. These stuff are usually used to teach students the recursion concept, not actual best practices. So the way you're doing it is just fine. Just don't use recursion in Java for these kind of stuff in real world apps ;)

PS. Aside what I just said, I'd choose "" as the base case of my recursive function:

public String reverseString(String s){
    if (s.length() == 0) 
         return s;
    return reverseString(s.substring(1)) + s.charAt(0);
}

Modified On Mar-15-2016 05:48:27 AM

Don't want to miss updates? Please click the below button!

Follow MindStick