一、由于String底层是字符数组,我们可以利用这一原理进行字符串反转
public class StringReverse {
public static void main(String[] args) {
String str1 = reverse("HellowWorld");
System.out.println(str1);
}
//方法一
public static String reverse(String str){
char[] ch = str.toCharArray();
for (int x = 0,y=ch.length-1; x <y ; x++,y--) {
char temp = ch[x];
ch[x] = ch[y];
ch[y] = temp;
}
return new String(ch);
}
}
二、利用StringBuilder类的reverse()实现字符串反转
//方法二
public static String reverse1(String str) {
StringBuilder stringBuilder = new StringBuilder(str);
StringBuilder str2 = stringBuilder.reverse();
return str2.toString();
}
二、利用StringBuilder类的append()实现字符串反转
//方法三
public static String reverse2(String str) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = str.length()-1; i >=0 ; i--) {
stringBuilder.append(str.charAt(i));
}
return stringBuilder.toString();
}