1.递归实现字符串反转
public static String reverseStr(String str) {
int length = str.length();
if (length <= 1) {
return str;
}
return reverseStr(str.substring(1)) + str.charAt(0);
}
2.charAt()
/**
* 该方法是通过charAt()方法获得每一个char的字符,
* i=0时获得第一个字符a然后赋值给reverse
* 此时reverse="a";i=1时获得第二个字符b
* 然后加上reverse再赋值给reverse,此时reverse="ba";
* 依次类推
*/
public static String reverseCharAt(String s) {
int length = s.length();
String reverse = "";
for (int i = 0; i < length; i++)
reverse = s.charAt(i) + reverse;
return reverse;
}
3.charArray
public static String reverseCharArray(String s) {
char[] array = s.toCharArray();
String reverse = "";
for (int i = array.length - 1; i >= 0; i--) {
reverse += array[i];
}
return reverse;
}
4.StringBuilder
/**
* StringBuilder 的reverse()
*
* @param s
* @return
*/
public static String reverseStringBuilder(String s) {
StringBuilder sb = new StringBuilder(s);
String reverseStr = sb.reverse().toString();
return reverseStr;
}
网友评论