Reverse a String
public class Q2_reverseString {
// Method 1: built in StringBuffer function
public static void reverseString(String str) {
for (String part : str.split(" ")) {
System.out.print(new StringBuffer(part).reverse().toString());
System.out.print(" ");
}
}
public static String reverse(String str_words) {
char[] c_array = str_words.toCharArray();
int pos_start = 0;
int pos_end;
char c, c_tmp;
int i, j, rev_length;
for (i = 0; i < c_array.length; i++) {
c = c_array[i];
if (c == ' ' || c == '\n') {
if (pos_start != i) {
pos_end = i - 1;
rev_length = (i - pos_start) / 2;
for (j = 0; j < rev_length; j++) {
c_tmp = c_array[pos_start + j];
c_array[pos_start + j] = c_array[pos_end - j];
c_array[pos_end - j] = c_tmp;
}
}
pos_start = i + 1;
}
}
// redundant, if only java had '\0' @ end of string
if (pos_start != i) {
pos_end = i - 1;
rev_length = (i - pos_start) / 2;
for (j = 0; j < rev_length; j++) {
c_tmp = c_array[pos_start + j];
c_array[pos_start + j] = c_array[pos_end - j];
c_array[pos_end - j] = c_tmp;
}
}
return new String(c_array);
}
public static String reverse(String in, String out) {
return (in.isEmpty()) ? out : (in.charAt(0) == ' ') ? out + ' '
+ reverse(in.substring(1), "") : reverse(in.substring(1),
in.charAt(0) + out);
}
public static String reverseSimple(String s) {
if (s == null || s.length() == 0)
return null;
int length = s.length(), 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 - i] = c;
}
return new String(chars);
}
}