作者LPH66 (IWH68S0XZ8M89)
看板java
标题Re: [问题] java的API--java.lang.String里的index …
时间Sun Mar 23 23:58:19 2008
※ 引述《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