java023字符串反转练习
方法1:
把字符串倒着遍历,得到的每一个字符拼接成字符串,代码如下:
package example;
import java.util.Scanner;
public class String_Test3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String ss = sc.nextLine();
String result = reverse(ss);
System.out.println("result:"+result);
}
public static String reverse(String ss){
String s = "";
for(int x=ss.length()-1;x>=0;x--){
s+=ss.charAt(x);
}
return s;
}
}
方法2:
把字符串转换为字符数组,然后对数组进行遍历,最后把字符数组转换为字符串。
package example;
import java.util.Scanner;
public class String_Test4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String ss = sc.nextLine();
String result = reverse(ss);
System.out.println("result:"+result);
}
public static String reverse(String ss){
char [] chs = ss.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 s = new String(chs);
return s;
}
}