Objects of the Java String class are immutable - their contents cannot be changed after creation.
You will need at least two temporary objects: one for the final result and one for intermediate values, even if you find a way to avoid using a local variable.
EDIT:
However, since you can use int[]
, you can cheat.
Since char
can be assigned int
, you can use String.charAt()
to create an int
array with character values ββin the reverse order. Or you may be allowed to use String.toCharArray()
to get a char
array that will be copied to your int[]
temporary.
Then you use a variable containing a reference to the source string (or a result variable if allowed) to start with an empty string (easy to get with the direct purpose or String.substring()
) and use String.concat()
to create the final result .
In any case, you cannot replace characters in place, as it would in C / C ++.
EDIT 2:
Here is my version that does not use StringBuffer / Builders inside:
int r[] = new int[s.length()]; int idx = r.length - 1; for (int i : s.toCharArray()) { r[idx--] = i; } s = s.substring(0, 0); for (int i : r) { s = s.concat(String.valueOf((char)i)); }
source share