方法1 递归方法
public static String reverse(String s) {
int length = s.length();
if (length <= 1){
return s;
}
String left = s.substring(0, length / 2);
String right = s.substring(length / 2, length);
return reverse(right) + reverse(left);
}
方法2 通过 charAt(int index)返回char值进行字符串拼接
public static String reverse(String s) {
int length = s.length();
String reverse = "";
for (int i = 0; i < length; i++)
reverse = s.charAt(i) + reverse;
return reverse;
}
方法3 调用StringBuffer中的reverse方法
public static String reverse(String s) {
return new StringBuffer(s).reverse().toString();
}
StringBuffer中的reverse方法源码
/* */ public AbstractStringBuilder reverse()
/* */ {
/* 1374 */ int i = 0;
/* 1375 */ int j = this.count - 1;
/* 1376 */ int m; int n; for (int k = j - 1 >> 1; k >= 0; k--) {
/* 1377 */ m = this.value[k];
/* 1378 */ n = this.value[(j - k)];
/* 1379 */ if (i == 0) {
/* 1380 */ i = ((m >= 55296) && (m <= 57343)) || ((n >= 55296) && (n <= 57343)) ? 1 : 0;
/* */ }
/* */
/* 1383 */ this.value[k] = n;
/* 1384 */ this.value[(j - k)] = m;
/* */ }
/* 1386 */ if (i != 0)
/* */ {
/* 1388 */ for (k = 0; k < this.count - 1; k++) {
/* 1389 */ m = this.value[k];
/* 1390 */ if (Character.isLowSurrogate(m)) {
/* 1391 */ n = this.value[(k + 1)];
/* 1392 */ if (Character.isHighSurrogate(n)) {
/* 1393 */ this.value[(k++)] = n;
/* 1394 */ this.value[k] = m;
/* */ }
/* */ }
/* */ }
/* */ }
/* 1399 */ return this;
/* */ }