Tuesday, April 27, 2010

Reverse a String in Java

Code for reversing a string in Java.

public static String reverse (String s) {
int length = s.length();
int last = length - 1;
char[] chars = s.toCharArray();
for (int i=0; i < length/2; i++){
char c = chars[i];
chars[i] = chars[last - i];
chars[last] = c;
}
return new String(chars);
}

No comments:

Post a Comment