一、使用 StringBuilder 或 StringBuffer 的 reverse 方法
他们的本质都是调用了它们的父类 AbstractStringBuilder 的 reverse 方法实现的(需要JDK1.8)
/**
* 使用StringBuilder的reverse()方法将字符串反转
*/
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("ABCDE牛");
System.out.println(sb.reverse());
}
输出结果:
二、自己实现反转代码
/**
* 自己实现字符串反转
*/
public static void main(String[] args) {
String str = "ABCDE牛";
//方式一 取出最后一个,然后一个一个复制给数组
char[] chars = new char[str.length()];
for (int i = str.length() - 1; i >= 0; i--) {
chars[str.length() - 1 - i] = str.charAt(i);
}
System.out.println(chars);
//方式二 截取出最后一个,然后一个一个输出
for(int i = str .length() -1 ; i>= 0; i--){
System.out.print(str.substring(i,i+1));
}
}
输出结果:
三、使用递归方式
/**
* 使用递归反转字符串
*/
public static void main(String[] args) {
String str = "ABCDE牛";
System.out.println(stringReversalRecursion(str));
}
/**
* 递归方法
*/
public static String stringReversalRecursion(String str) {
if (str == null || str.length() <= 1) {
return str;
}
return stringReversalRecursion(str.substring(1)) + str.charAt(0);
}
输出结果: