在StringBuffer中实现了字符串反转的方法。
public static String reverse(String str) {
return str == null ? null : (new StringBuffer(str)).reverse().toString();
}
实现
StringBuffer的父类是AbstractStringBuilder
public AbstractStringBuilder reverse() {
boolean hasSurrogates = false;
//数组下标最大的长度
int n = count - 1;
for (int j = (n-1) >> 1; j >= 0; j--) {
// 调换字符顺序
int k = n - j;
char cj = value[j];
char ck = value[k];
value[j] = ck;
value[k] = cj;
//处理特殊字符的,先不用关心。
if (Character.isSurrogate(cj) ||
Character.isSurrogate(ck)) {
hasSurrogates = true;
}
}
if (hasSurrogates) {
reverseAllValidSurrogatePairs();
}
return this;
}
精简来看:
/**
* The value is used for character storage.
* 字符存储的值
*/
char[] value;
/**
* The count is the number of characters used.
* 字符的数量
*/
int count;
public AbstractStringBuilder reverse() {
int n = count - 1;
for (int j = (n-1) >> 1; j >= 0; j--) {
int k = n - j;
char cj = value[j];
char ck = value[k];
value[j] = ck;
value[k] = cj;
}
return this;
}
简单记录下
网友评论