WHAT IS THE FINEST METHOD TO RECURSIVELY REVERSE A STRING IN JAVA?

Goti Bandu

Total Post:119

Points:835
Posted by  Goti Bandu
Java 
 918  View(s)
Ratings:
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));
    }

 

  1. jacob rasel

    Post:88

    Points:616
    Re: What is the finest method to recursively reverse a string in Java?

    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!