实现字符串的反转有两种办法
- 第一个就是使用JDK自带的reversal()方法。但是注意 String类不能直接使用这个方法,需要把字符串转换成StirngBuilder或者StringBuffer才能调用
上代码
public class Test02 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入一个字符串");
String str = scanner.nextLine();
StringBuilder stringBuilder = new StringBuilder(str);
StringBuilder reverse = stringBuilder.reverse();
System.out.println(reverse);
}
}
- 第二种方式是通过String类写一个反转的方法,通过for循环进行反转
上代码
import java.util.Scanner;
public class Test02 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入一个字符串");
String str = scanner.nextLine();
StringBuilder stringBuilder = new StringBuilder(str);
StringBuilder reverse = stringBuilder.reverse();
System.out.println(reverse);
}
}