-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.

Shashank Shekher
  • 797
  • 1
  • 8
  • 25

1 Answers1

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);
apetranzilla
  • 5,331
  • 27
  • 34