我正在尝试理解Java中的一些String类函数.所以,这是一个简单的代码:
/* different experiments with String class */
public class TestStrings {
public static void main(String[] args) {
String greeting = "Hello\uD835\uDD6b";
System.out.println("Number of code units in greeting is " + greeting.length());
System.out.println("Number of code points " + greeting.codePointCount(0,greeting.length()));
int index = greeting.offsetByCodePoints(0,6);
System.out.println("index = " + index);
int cp = greeting.codePointAt(index);
System.out.println("Code point at index is " + (char) cp);
}
}
Run Code Online (Sandbox Code Playgroud)
\ uD835\uDD6b是一个ℤ符号,所以它是好的代理对.
因此,该字符串具有6(6)个代码点和7(7)个代码单元(2字节字符).正如文档中所述:
offsetByCodePointsRun Code Online (Sandbox Code Playgroud)public int offsetByCodePoints(int index, int codePointOffset)返回此String中的索引,该索引由codePointOffset代码点从给定索引偏移.index和codePointOffset给出的文本范围内的不成对代理计为每个代码点.
参数:
index- 要抵消的指数
codePointOffset- 代码点的偏移量
所以我们在代码点中给出一个参数.但是,使用给定的参数(0,6)它仍然可以正常工作,没有例外.但是对于codePointAt()失败了,因为它返回7超出范围.那么,也许该函数以代码单位获取其args?或者我错过了什么.
codePointAt拿一个char索引.
该指数指的是从char值(Unicode代码单位)和范围
0来length() - 1.
该字符串中有六个代码点.该offsetByCodePoints调用在6个代码点(char-index 7)之后返回索引.然后尝试获取codePointAt(7)字符串末尾的代码.
要明白原因,请考虑一下
"".offsetByCodePoints(0, 0) == 0
Run Code Online (Sandbox Code Playgroud)
因为要计算所有0个代码点,你必须计算所有0 char秒.
将其推断到您的字符串,计算超过所有6代码点,您必须计算所有7 char秒.
也许codePointAt在使用中会明白这一点.这是迭代字符串(或CharSequence)中所有代码点的惯用方法:
for (var charIndex = 0, nChars = s.length(), codepoint;
charIndex < nChars;
charIndex += Character.charCount(codepoint)) {
codepoint = s.codePointAt(charIndex);
// Do something with codepoint.
}
Run Code Online (Sandbox Code Playgroud)