1、方法一:使用现有的方法reverse()
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);String s1 = sc.nextLine();
StringBuffer s2 = new StringBuffer(s1);
StringBuffer s3 = s2.reverse();
System.out.println(s3);
}
结果是:
12345
54321
2、方法二:使用栈将字符串一个个压入,再弹出
public static void main(String[] args) {
String s = change("12345");
System.out.println(s);
}
public static String change(String s1){
String result ="";
Stack stack = new Stack();
for(int i=0;i<s1.length();i++){
stack.push(s1.charAt(i));
}
int len = s1.length();
while(!stack.isEmpty()){
result += stack.pop();
}
return result;
}
结果是: 54321