2011-12-15 137 views
4

我想了解一些在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出界。所以,也許該函數獲取代碼單元的參數?或者我錯過了一些東西。

回答

5

codePointAt需要char索引。

該索引引用char值(Unicode代碼單元),範圍從0length() - 1

該字符串中有六個代碼點。調用offsetByCodePoints將返回6個代碼點之後的索引,即char-index 7.然後嘗試獲取位於該字符串末尾的codePointAt(7)

想知道爲什麼,考慮什麼

"".offsetByCodePoints(0, 0) == 0 

因爲計算過去所有0碼點,你要算過去所有0 char秒。

將其推斷爲您的字符串,要計算過去所有6代碼點,您必須計算過去所有的7 char s。

在使用中可能會看到codePointAt會使這一點變得清晰。這是遍歷所有代碼點在字符串中的慣用方式(或CharSequence):

for (var charIndex = 0, nChars = s.length(), codepoint; 
    charIndex < nChars; 
    charIndex += Character.charCount(codepoint)) { 
    codepoint = s.codePointAt(charIndex); 
    // Do something with codepoint. 
} 
+0

謝謝!但關於討論代碼的*奇怪的事情是int index = greeting.offsetByCodePoints(0,6);實際上不是6,而是7!這看起來很奇怪,假設代碼點的最大代碼單元的索引是6和5(從0開始計數)。 – 2011-12-15 17:45:30

0

有用的答案,邁克......爲了便於理解String#offsetByCodePoints,我評論它的使用和修改了一下這個問題例如:

我個人發現這裏的Java文檔含糊不清。

public class TestStrings 
{ 
    public static void main(String[] args) 
    { 
     String greeting = "Hello\uD835\uDD6b"; 

     // Gets the `char` index a.k.a. offset of the code point 
     // at the code point index `0` starting from the `char` index `6`¹. 
     // --- 
     // Since `6` refers to an "unpaired" low surrogate (\uDD6b), the 
     // returned value is 6 + 1 = 7. 
     // 
     int charIndex = greeting.offsetByCodePoints(0,6); 

     System.out.println("charIndex = " + charIndex); 

     int cp = greeting.codePointAt(charIndex); 
     System.out.println("Code point at index is " + (char) cp); 
    } 
} 
相關問題