字符串逆序输出的几种方式
1.利用StringBuilder ,StringBuffer实现翻转
String test = "wangguoshun";
StringBuilder sb = new StringBuilder();
StringBuilder reverse = sb.append(test).reverse();
//System.out.println(reverse);
StringBuffer sb2 = new StringBuffer();
StringBuffer reverse2 = sb2.append(test).reverse();
System.out.println(reverse2);
2.转为数组,逆序循环输出:
String test = "wangguoshun";
char[] array = test.toCharArray();
System.out.println(array.length);
for(int i=array.length-1;i>=0;i--) {
System.out.println(array[i]);
}
3.这种方法稍微有点意思儿的:借助一个中间变量实现两边变量位置的互换。
String test = "wangguoshun";
char[] array = test.toCharArray();
System.out.println("hfsk"+array.length/2);
for (int i = 0; i < array.length/2; i++) {
char temp;
temp = array[i];
array[i]=array[array.length-i-1];
array[array.length-i-1]=temp;
}
System.out.println(new String(array));
System.out.println("----------------");