+ 2
In reverse a string code in java, what is the meaning of this line? String rev = ""; Please explain.
2 Answers
+ 3
We generally create an empty string.
String rev = "";
Then traverse over the original string from the last character and concat it to the string rev until you reach the first character.
It basically stores your reversed string.
+ 2
I remember trying to work through the reversing a string challenge. I could not seem to get it through my head that strings in Java are immutable. I also didn't know I could use StringBuffer and StringBuilder. I didn't really need to create a new string object, I could have just printed it. But the code worked, even though getting there made me nuts đ
char[] arr = text.toCharArray();
for(int i=0; i<arr.length/2; i++)
{
char character = arr[i];
arr[i] = arr[arr.length -i -1];
arr[arr.length -i -1] = character;
}
String reversed = new String(arr);
System.out.print(reversed);