public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String s = sc.nextLine();
System.out.println("反转后的字符串:"+reverse(s));
}
//反转字符串
//返回类型:String
//参数:String s
//1.使用charAt倒着遍历字符串
/*public static String reverse(String s) {
String ss = "";
for(int i=s.length()-1;i>=0;i--) {
ss += s.charAt(i);
}
return ss;
}*/
//2.使用toCharArray()先将字符串转化为字符数组,再交换,之后转回字符串。
public static String reverse(String s) {
char[] chs = s.toCharArray();
for(int start=0,end=chs.length-1;start<=end;start++,end--) {
char temp = chs[start];
chs[start] = chs[end];
chs[end] = temp;
}
String ss = new String(chs);//把字符数组转化为字符串
return ss;
}
}
//3.StringBuilder的reverse()方法
public class stringbuilder {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("hello").append("world").append(true).append(100);
System.out.println(sb);
System.out.println("反转后的字符串"+sb.reverse());
}
}