目录
法一(拆分字符数组):
public class MyTest {
public static void main(String[] args) {
String s = "abbdfaadqwedqfdad";
//字符串转化为字符数组
char[] charArray = s.toCharArray();
char[] chars = new char[s.length()];
for (int i = 0; i < charArray.length; i++) {
chars[i] = charArray[charArray.length - i - 1];
}
//直接利用字符串的构造方法将字符数组转化为字符串
String s1 = new String(chars);
System.out.println(s1);
}
}
法二(利用字符串串联符号”+”特性):
- 字符串+特性还可参考下面
字符串加号拼接时,系统底层是创建StringBuilder对象然后调用append()拼接再通过toString()转换为String类型最后存于堆内存
public class MyTest {
public static void main(String[] args) {
String s = "abbdfaadqwedqfdad";
String s2 = "";
for (int i = s.length() - 1; i >= 0; i--) {
s2 += s.charAt(i);
}
System.out.println(s2);
}
}
}
法三(StringBuilder的reverse()方法):
public static void main(String[] args) {
String s = "abbdfaadqwedqfdad";
StringBuilder stringBuilder = new StringBuilder(s);
stringBuilder.reverse();
String s1 = stringBuilder.toString();
System.out.println(s1);
}