将字符串按照单词完全反转过来,如"abc"反转为"cba"

2014-11-24 10:14:18 · 作者: · 浏览: 0
这是面试常考到的一道题,那我们就以一个包含26个英文字母的字符串作为实例,进行解答
[java]
public class StringReverse {
public static void main(String[] args) {
// 原始字符串(The First Method)
String str = "Hello World";
System.out.println("原始字符串: " + str);
System.out.print("反转后的字符串: ");
for (int i = str.length(); i > 0; i--) {
System.out.print(str.charAt(i - 1));
}
System.out.println();
System.out.println("####################################");
// The Second Method
StringBuffer sb = new StringBuffer(str);
System.out.println("原始字符串: " + str);
System.out.print("反转后的字符串: ");
System.out.print(sb.reverse().toString());
}
}