-4

Suppose there is a string variable str = "A man is no one!", then i need the reverse of this string to be stored in same str variable as "!eno on si nam A", without using any other object or variable. Could someone please provide the most optimized way to do this?

I already used below piece of code:

public static String reverseRecursively(String str) {
        //base case to handle one char string and empty string
        if (str.length() < 2) {
            return str;
        }
        return reverseRecursively(str.substring(1)) + str.charAt(0);
    }

Any other way of doing this?

Please note that I only want it using String class methods.

1
  • Could you provide your not optimized way? Commented Aug 8, 2016 at 17:33

1 Answer 1

2

Try this.

new StringBuilder(str).reverse().toString()

While this does create a new StringBuilder instance, it doesn't store it in a variable, and it would be very tricky (if possible) to reverse the string without ANY new objects whatsoever.

Edit

Since you don't want to use anything but String methods, here's a simple way to do it with a loop instead, but again it still creates new objects.

char[] chars = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
    chars[str.length() - i - 1] = str.charAt(i);
}
String newStr = new String(chars);
Sign up to request clarification or add additional context in comments.

7 Comments

I do not want to use StringBuilder. I want to reverse using only String class methods.
@ShashankShekher I've updated my answer.
Any other solution?
@ShashankShekher What's wrong with the one I just made? What are the requirements?
Nothing wrong. Just want to know if there's any other approach.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.