我想了解一些在Java中的String類的功能。所以,這裏是一個簡單的代碼:什麼Java函數offsetByCodePoints真的需要作爲參數?
/* 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);
}
}
\ uD835 \ uDD6b是ℤ象徵,所以這是確定代理對。
所以,字符串有6(6)個代碼點和7(7)個代碼單元(2字節的字符)。由於它在文檔:
offsetByCodePoints
public int offsetByCodePoints(int index, int codePointOffset)
返回此字符串,它是由代碼codePointOffset個點給定索引偏移中的索引。 由index和codePointOffset給出的文本範圍內的未配對替代項每個都計爲一個代碼點。
參數:
index
- 要抵消
codePointOffset
指數 - 中碼點的偏移
所以我們做讓步代碼點參數。但是,對於給定的參數(0,6),它仍然正常工作,沒有例外。但codePointAt()失敗,因爲它返回7出界。所以,也許該函數獲取代碼單元的參數?或者我錯過了一些東西。
謝謝!但關於討論代碼的*奇怪的事情是int index = greeting.offsetByCodePoints(0,6);實際上不是6,而是7!這看起來很奇怪,假設代碼點的最大代碼單元的索引是6和5(從0開始計數)。 – 2011-12-15 17:45:30