最近,我遇到了Java中的String类的codePointAt方法。我还发现了其他一些codePoint方法:codePointBefore
,codePointCount
等。它们肯定与Unicode有关,但我并不理解。
现在我想知道何时以及如何使用codePointAt
和类似的方法。
最近,我遇到了Java中的String类的codePointAt方法。我还发现了其他一些codePoint方法:codePointBefore
,codePointCount
等。它们肯定与Unicode有关,但我并不理解。
现在我想知道何时以及如何使用codePointAt
和类似的方法。
简短回答: 它给出了在String
中指定索引处开始的Unicode代码点。 即该位置字符的“Unicode编号”。
更详细的解释: Java创建时只使用16位(也称为char
)就足以容纳任何已存在的Unicode字符(这些部分现在被称为基本多语言面板或BMP)。 稍后,Unicode扩展以包括具有大于2 16 的代码点的字符。 这意味着char
不再能够保存所有可能的Unicode代码点。
UTF-16是解决方案:它将“旧”Unicode代码点存储在16位中(即恰好一个char
),并将所有新的Unicode代码点存储在32位中(即两个char
值)。这两个16位值被称为“代理对”。现在严格来说,char
保存的是“UTF-16代码单元”而不是“Unicode字符”,就像以前一样,所有“旧”的方法(仅处理char
)仍然可以正常使用,只要您不使用任何“新”的Unicode字符(或者根本不关心它们),但是如果您也关心新字符(或者需要完整的Unicode支持),那么您将需要使用“代码点”版本,它实际上支持所有可能的Unicode代码点。
char
表示。下面的代码示例有助于澄清使用codePointAt
的方法
String myStr = "13";
System.out.println(myStr.length()); // print 4, because is two char
System.out.println(myStr.codePointCount(0, myStr.length())); //print 3, factor in all unicode
int result = myStr.codePointAt(0);
System.out.println(Character.toChars(result)); // print 1
result = myStr.codePointAt(1);
System.out.println(Character.toChars(result)); // print , because codePointAt will get surrogate pair (high and low)
result = myStr.codePointAt(2);
System.out.println(Character.toChars(result)); // print low surrogate of only, in this case it show "?"
result = myStr.codePointAt(3);
System.out.println(Character.toChars(result)); // print 3
比较char和代码点? http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Character.html http://javarevisited.blogspot.com/2012/01/java-string-codepoint-get-unicode.html
希望这能帮助澄清问题 :)
charAt()
无法提供完整的代码点,但是codePointAt()
可以成功地提供。 - Zaid Khan