反转字符串一直被当作是简单问题,大家的思想主要就是利用遍历,首尾交换字符实现字符串的反转。例如下面的代码,就可以简单实现反转。
public static String reverse(char[] value) {
for (int i = (value.length - 1) >> 1; i >= 0; i--) {
char temp = value[i];
value[i] = value[value.length - 1 - i];
value[value.length - 1 - i] = temp;
}
return new String(value);
}
这样的代码,在算法方面是没有任何问题的。但是今天在查看StringBuilder源代码的时候发现,其中reverse方法的源代码写的很精妙。其实现方式是在父类AbstractStringBuilder中,源代码如下:
/**
* Causes this character sequence to be replaced by the reverse of
* the sequence. If there are any surrogate pairs included in the
* sequence, these are treated as single characters for the
* reverse operation. Thus, the order of the high-low surrogates
* is never reversed.
*
* Let <i>n</i> be the character length of this character sequence
* (not the length in {@code char} values) just prior to
* execution of the {@code reverse} method. Then the
* character at index <i>k</i> in the new character sequence is
* equal to the character at index <i>n-k-1</i> in the old
* character sequence.
*
* <p>Note that the reverse operation may result in producing
* surrogate pairs that were unpaired low-surrogates and
* high-surrogates before the operation. For example, reversing
* "\u005CuDC00\u005CuD800" produces "\u005CuD800\u005CuDC00" which is
* a valid surrogate pair.
*
* @return a reference to this object.
*/
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;
}
/** Outlined helper method for reverse() */
private void reverseAllValidSurrogatePairs() {
for (int i = 0; i < count - 1; i++) {
char c2 = value[i];
if (Character.isLowSurrogate(c2)) {
char c1 = value[i + 1];
if (Character.isHighSurrogate(c1)) {
value[i++] = c1;
value[i] = c2;
}
}
}
}
其中reverse()方法使用的Character.isSurrogate(char ch)方法的源码如下:
/**
* Determines if the given {@code char} value is a Unicode
* <i>surrogate code unit</i>.
*
* <p>Such values do not represent characters by themselves,
* but are used in the representation of
* <a href="#supplementary">supplementary characters</a>
* in the UTF-16 encoding.
*
* <p>A char value is a surrogate code unit if and only if it is either
* a {@linkplain #isLowSurrogate(char) low-surrogate code unit} or
* a {@linkplain #isHighSurrogate(char) high-surrogate code unit}.
*
* @param ch the {@code char} value to be tested.
* @return {@code true} if the {@code char} value is between
* {@link #MIN_SURROGATE} and
* {@link #MAX_SURROGATE} inclusive;
* {@code false} otherwise.
* @since 1.7
*/
public static boolean isSurrogate(char ch) {
return ch >= MIN_SURROGATE && ch < (MAX_SURROGATE + 1);
}
在StringBuilder中的调用方式比较简单,如下:
@Override
public StringBuilder reverse() {
super.reverse();
return this;
}
从方法的内容来看,源代码中的基本思路是一致的,同样采用遍历一半字符串,然后将每个字符与其对应的字符进行交换。但是有不同之处,就是要判断每个字符是否在Character.MIN_SURROGATE(\ud800)和Character.MAX_SURROGATE(\udfff)之间。
如果发现整个字符串中含有这种情况,则再次从头至尾遍历一次,同时判断value[i]是否满足Character.isLowSurrogate(),如果满足的情况下,继续判断value[i+1]是否满足Character.isHighSurrogate(),如果也满足这种情况,则将第i位和第i+1位的字符互换。
可能有的人会疑惑,为什么要这么做,因为Java中的字符已经采用Unicode代码,每个字符可以放下一个汉字。为什么还要这么做?
一个完整的 Unicode 字符叫代码点CodePoint,而一个 Java char 叫 代码单元 code unit。String 对象以UTF-16保存 Unicode 字符,需要用2个字符表示一个超大字符集的汉字,这这种表示方式称之为 Surrogate,第一个字符叫 Surrogate High,第二个就是 Surrogate Low。具体需要注意的事宜如下:
- 判断一个char是否是Surrogate区的字符,用Character的 isHighSurrogate()/isLowSurrogate()方法即可判断。从两个Surrogate High/Low 字符,返回一个完整的 Unicode CodePoint 用 Character.toCodePoint()/codePointAt()方法。
- 一个Code Point,可能需要一个也可能需要两个char表示,因此不能直接使用 CharSequence.length()方法直接返回一个字符串到底有多少个汉字,而需要用String.codePointCount()/Character.codePointCount()。
- 要定位字符串中的第N个字符,不能直接将N作为偏移量,而需要从字符串头部依次遍历得到,需要用String/Character.offsetByCodePoints() 方法。
- 从字符串的当前字符,找到上一个字符,也不能直接用offset-- 实现,而需要用 String.codePointBefore()/Character.codePointBefore(),或用 String/Character.offsetByCodePoints()
- 从当前字符,找下一个字符,不能直接用 offset++实现,需要判断当前 CodePoint的长度后,再计算得到,或用String/Character.offsetByCodePoints()。
关于字符详细说明,请查看https://www.cnblogs.com/wanlipeng/archive/2011/01/27/1946435.html
原文出处:https://www.cnblogs.com/wanlipeng/archive/2011/01/27/1946441.html