kaibuki kaibuki - 2 months ago 11
Java Question

Reverse String in Java without using any Temporary String,Char or String Builder

Is it possible to reverse

String
in Java without using any of the temporary variables like
String
,
Char[]
or
StringBuilder
?

Only can use
int
, or
int[]
.

Answer
String reverseMe = "reverse me!";
for (int i = 0; i < reverseMe.length(); i++) {
    reverseMe = reverseMe.substring(1, reverseMe.length() - i)
        + reverseMe.substring(0, 1)
        + reverseMe.substring(reverseMe.length() - i, reverseMe.length());
 }
 System.out.println(reverseMe);

Output:

!em esrever

Just for the fun of it, of course using StringBuffer would be better, here I'm creating new Strings for each Iteration, the only difference is that I'm not introducing a new reference, and I've only an int counter.

Comments