package com.itheima.day08;
import java.util.Scanner;
//定义一个方法reverse(),实现字符串反转。键盘录入一个字符串,调用该方法后,在控制台输出结果
//例如: 键盘录入 abc,输出结果 cba
//版本一: String的逆向遍历,然后拼接.
//版本二: StringBuilder#reverse();
public class Work05 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入字符串");
String s= sc.nextLine();
System.out.println("String的逆向遍历;"+toStringReverse(s));
System.out.println("StringBuilder#reverse方法;"+toStringBuilderReverse(s));
}
public static String toStringReverse(String s){
String s1="";
for (int i = s.length()-1; i>=0; i--) {
s1+=s.charAt(i);
}
return s1;
}
public static StringBuilder toStringBuilderReverse(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb;
}
}
|
|