一个完整的Unicode字符叫代码点/CodePoint
代码点(CodePoint):一个完整的Unicode叫代码点
代码单元(CodeUnit):一个java char叫代码单元
Java的String对象是以UTF-16保存Unicode的字符,需要用2个字符表示一个超大字符集汉字,这种表示方式为Sruuogate,
第一个字符叫Surrogate High
第二个就是Surrogate Low
判断一个char是否是Surrogate区的字符,用Character的isHighSurrogate()/isLowSurrogate()方法。
从两个Surrogate High/Low字符,返回一个完整的Unicode CodePoint用Character.toCodePoint()/codePointAt()
一个代码点,可能需要一个也可能需要两个char表示,因此不能直接使用CharSequence.length()方法返回
一个字符串到底有多少个汉字,而需要用String.codePointCount()/Character.codePointCount()
要定位字符串中的第N个字符,不能直接将n作为偏移量,而需要从字符串头部依次遍历得到,需要String.offsetByCodePoints()
从字符串的当前字符,找到上一个字符,不能直接用offset实现,而需要String.codePointBefore(),或String.offsetByCodePoints()
从当前字符,找下一个字符,需要判断当前CodePoint的长度,再计算得到String.offsetByCodePoints()
举例:
String str = "web开发";
int len = str.length();
System.out.println(len);
//输出结果为5;
int cLen = str.codePointCount(0,str.length());
System.out.println(cLen );
//输出结果同样为5
//定位一个字符
char cp = str.charAt(4);
System.out.println(cp );
//输出为“发”;
int index = str.offsetByCodePoints(0,4);
int _cp = str.codePointAt(index);
System.out.println(_cp );
//输出为21457;
//原来是获取字符串中指定位置的字符的UNICODE值,其值等同于(int)charAt(i)