1.递归实现
public static String reverse(String original){
if(original==null|| original.length()<=1)
return original;
return reverse(original.substring(1))+original.charAt(0);
}
2.String的一些方法
public class test{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入:");
String s1 = input.nextLine();//得到输入的字符串
System.out.print("翻转后:");
for(int i=s1.length()-1;i>=0;i--){
//charAt()返回指定索引处的 char 值。索引范围为从 0 到 length() - 1
System.out.print(s1.charAt(i));
}
}
}
或者
import java.util.*;
public class StringChange{
public static void main(String[] args){
System.out.println("Please enter the String:");
String str = new Scanner(System.in).nextLine(); //输入字符串
String s2[] = str.split("\\s"); // \s 以空格为分隔符拆分字符串,并保存到数组s2里面
for (int i = s2.length-1; i >= 0; i--) { //反向输出数组
System.out.print(s2[i]+" ");
}
}
}
3.利用StringBuffer的内置reverse方法
public static String reverse2(String s){
String str;
StringBuffer sbBuffer =new StringBuffer(s);
str=sbBuffer.reverse().toString();
return str;
}