code unit和code point

来源:互联网 发布:程序员 量化交易 入门 编辑:程序博客网 时间:2024/06/05 06:45

一个完整的Unicode字符叫代码点/CodePoint,而一个Java char 叫代码单元code unit;

string对象以UTF-16保存Unicode字符,需要用2个字符表示一个超大字符集汉字,这种表示方式为
Sruuogate,第一个字符叫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.offsetByCodePoints()
从字符串的当前字符,找到上一个字符,不能直接用offset实现,而需要
String.codePointBefore(),或String.offsetByCodePoints()
从当前字符,找下一个字符,需要判断当前CodePoint的长度,再计算得到
String.offsetByCodePoints()

看了之后还是不太明白

String str("web开发");

int len = str.length();

System.out.println();

输出结果为5;

改为用int len = str.codePointCount(0,str.length());

输出结果同样为5

定位一个字符

用char cp = str.charAt(4);

输出为“发”;

若用int index = str.offsetByCodePoints(0,4);

       int cp = str.codePointAt(index);

输出为21457;什么意思??原来是获取字符串中指定位置的字符的UNICODE值,其值等同于(int)charAt(i)


1 0
原创粉丝点击