倒序输出字符串
public static void main(String[] args) {
String str = "!xc doog";
String[] content = str.split(" ");
String result = "";
for (String s : content) {
result +=revertString(s);
}
System.out.println(result);
}
public static String revertString(String str) {
if (str == null) {
return null;
}
char[] chars = str.toCharArray();
int len = chars.length;
int half = len/2;
char first;
for (int i = 0; i < half; i++) {
first = chars[i];
chars[i] = chars[len-1-i];
chars[len-1-i] = first;
}
return new String(chars);
}
输出
结果:cx!good
原理:将需要倒序的字符串对半分割,然后第一个字符和最后一个字符交换位置,循环便利依次交换,最后得到结果。