法一(拆分字符数组):
import java.util.*;
public class Main {
public static void main(String[] args) {new Main().test();}
void test() {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
char[] charArray = s.toCharArray();
char[] chars = new char[s.length()];
for(int i = 0;i < s.length();i++){
chars[i] = charArray[s.length()-i-1];
}
// 直接利用字符串的构造方法将字符数组转化为字符串
String s1 = new String(chars);
System.out.println(s1);
// for(char c : chars){
// System.out.printf("%c",c);
// }
// 直接利用字符串的构造方法将字符数组转化为字符串
}
法二(利用字符串串联符号"+"特性):
import java.util.*;
public class Main {
public static void main(String[] args) {new Main().test();}
void test() {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = "";
for(int i = s1.length()-1;i >= 0;i--){
char c = s1.charAt(i);
s2 += c;
}
System.out.println(s2);
}
法三(StringBuilder的reverse()方法):
import java.util.*;
public class Main {
public static void main(String[] args) {new Main().test();}
void test() {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
StringBuilder stringBuilder = new StringBuilder(s1);
stringBuilder.reverse();
String s2 = stringBuilder.toString();
System.out.println(s2);
}
}
Java算法中字符串反序的三种方法
最新推荐文章于 2024-05-21 11:15:00 发布
关键词由CSDN通过智能技术生成