this question has answer here:
- reverse string in java 34 answers
suppose there string variable str = "a man no one!"
, need reverse of string stored in same str variable "!eno on si nam a"
, without using other object or variable. please provide optimized way this?
i used below piece of code:
public static string reverserecursively(string str) { //base case handle 1 char string , empty string if (str.length() < 2) { return str; } return reverserecursively(str.substring(1)) + str.charat(0); }
any other way of doing this?
please note want using string class methods
.
try this.
new stringbuilder(str).reverse().tostring()
while create new stringbuilder instance, doesn't store in variable, , tricky (if possible) reverse string without new objects whatsoever.
edit
since don't want use string
methods, here's simple way loop instead, again still creates new objects.
char[] chars = new char[str.length()]; (int = 0; < str.length(); i++) { chars[str.length() - - 1] = str.charat(i); } string newstr = new string(chars);
Comments
Post a Comment