Re: [問題] java的API--java.lang.String裡的index …

看板java作者 (IWH68S0XZ8M89)時間16年前 (2008/03/23 23:58), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/3 (看更多)
※ 引述《king19880326 (OK的啦~我都可以接受)》之銘言: : 我看官網的API文件 : 裡面對於java.lang.String裡的indexOf()是這麼下參數的 : public int indexOf(int ch)<--int而不是char : 這是不是他打錯了啊 囧> : 還是我的觀念有問題勒OTZ 你沒有仔細看完。 ========== 以下是 API 內容 ============ For values of ch in the range from 0 to 0xFFFF (inclusive), this is the smallest value k such that: this.charAt(k) == ch is true. For other values of ch, it is the smallest value k such that: this.codePointAt(k) == ch is true. ======================================= charAt和codePointAt的差別在於 如果指的字是Unicode中的surrogate pair的話 charAt是回傳那個surrogate pair的值 (所以一定是個char) codePointAt是回傳那一對surrogate pair所指的unicode (所以可能會超過char) (unicode的字碼有定到U+10FFFF 不過只有一小部份的U+1xxxx和U+2xxxx目前有定義字元 以及U+E0000之後的都是private use 所以用到的很少 不過有些字就要在那裡才有 例如U+1D11E是一個高音譜記號) 所以 如果你傳一個<=65535的值給indexOf 它會認為你要找單個unicode 傳>65535的值進去的話就會去找那個surrogate pair的位置 例如: class Test { public static void main(String[] args) { //U+D800 U+DC00這個surrogate pair表示U+10000 String s="\ud800\udc00"; int a=s.charAt(0); int b=s.codePointAt(0); //以下會印出a=0xd800 b=0x10000 System.out.println("a=0x"+Integer.toHexString(a)); System.out.println("b=0x"+Integer.toHexString(b)); //U+D800 U+DC01表示U+10001 String t="\ud800\udc01\ud800\udc00"; //找U+D800的位置 int c=t.indexOf(0xd800); //找表示U+10000的surrogate pair(即U+D800 U+DC00)的位置 int d=t.indexOf(0x10000); //以下會印出c=0 d=2 System.out.println("c="+c); System.out.println("d="+d); } } -- **** 說: 不要期望一個精神力差不多已經見底的人阿Orz -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.30.84
文章代碼(AID): #17vduTG2 (java)
文章代碼(AID): #17vduTG2 (java)