题解 | #字符串反转#
字符串反转
https://www.nowcoder.com/practice/e45e078701ab4e4cb49393ae30f1bb04
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
//调用stringbuffer的翻转方法
String a = in.nextLine();
StringBuffer sb = new StringBuffer(a);
System.out.println(sb.reverse());
}
}
}
一、使用 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());
}
12345678
输出结果:

二、自己实现反转代码
/**
* 自己实现字符串反转
*/
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));
}
}
12345678910111213141516
输出结果:

三、使用递归方式
/**
* 使用递归反转字符串
*/
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);
}
1234567891011121314151617
输出结果:

