反转字符串有三种方式:
- 通过StringBuiler或者StringBuffer的reverse方法反转字符串
- 使用charAt遍历所有字符的值,进行反向拼接
- 转成数组,反向遍历数组
public class TestStringReserve {
static String a="abcdefg";
@Test
public void test1(){
// 如果是StringBuiler或者StringBuffer,那么调用reverse方法就可以反转字符串
StringBuilder sb=new StringBuilder("abcdefg");
sb.reverse();
System.out.println(sb);
}
@Test
public void tes2(){
int length=a.length();
// reverse为空字符串
String reverse="";
// 正向遍历字符串
for (int i = 0; i < length; i++) {
// 使用charAt正向遍历所有的值,把后遍历出来的值放在前面
reverse=a.charAt(i)+reverse;
}
System.out.println(reverse);
}
@Test
public void test3(){
// 将字符串通过toCharArray方法改写成array数组
char []array=a.toCharArray();
String reverse="";
// 遍历数组,从后往前排序
for (int i = array.length-1; i >=0 ; i--) {
reverse+=array[i];
}
System.out.println(reverse);
}
}