Java字符串的代码点和代码单元

来源:互联网 发布:windows 10 ltsb iso 编辑:程序博客网 时间:2024/06/02 02:08
  • 代码点:指可用于编码字符集的数字。
  • 代码单元:存储代码点的空间。

首先简单解释下其产生的背景,计算机最初诞生的时候,只有ASCII编码用来表示一些英文字符,随着计算机的普及,也伴随这一些编码的产生,如中国的GB2312、西欧语言中的ISO 8859-1等。随后出现的Unicode字符编码希望创建一个可以表示世界上所有字符的语言字典,其最初设计的时候使用两个字节表示,在开始启动设计工作时,人们认为两个字节的代码宽度足以能够对世界上各种语言的所有字符进行编码,并有足够的空间留给未来的扩展。经过一段时间,不可避免的事情发生了,Unicode字符超过了65536个,这个道理就像随着互联网的普及IPv4地址不够用一样。
在最初设计Java时决定采用两个字节的char型来表示16位的Unicode字符,当然那时候还么有出现Unicode字符不够用的情况,后来由于出现Unicode字符不够用的情况,Unicode字符增加了字符补集,辅助字符采用对连续的代码单元进行编码。
下面是摘自JDK8中的一段话:

The char data type (and therefore the value that a Character object encapsulates) are based on the original Unicode specification, which defined characters as fixed-width 16-bit entities. The Unicode Standard has since been changed to allow for characters whose representation requires more than 16 bits. The range of legal code points is now U+0000 to U+10FFFF, known as Unicode scalar value. (Refer to the definition of the U+n notation in the Unicode Standard.)
The set of characters from U+0000 to U+FFFF is sometimes referred to as the Basic Multilingual Plane (BMP). Characters whose code points are greater than U+FFFF are called supplementary characters. The Java platform uses the UTF-16 representation in char arrays and in the String and StringBuffer classes. In this representation, supplementary characters are represented as a pair of char values, the first from the high-surrogates range, (\uD800-\uDBFF), the second from the low-surrogates range (\uDC00-\uDFFF).

大概意思是:
char数据类型(因此字符对象封装的值)基于原来的Unicode规范,该字符定义为固定宽度的16位实体的字符。Unicode标准从此更改为允许其表示需要超过16位的字符。代码点范围现在是U + 0000到u + 10ffff。
从u + 0000至U+FFFF之间的字符集是有时被称为基本多文种平面(BMP)。字符的编码点大于U+FFFF之间称为增补字符。java平台使用UTF-16表示的字符数组和字符串和StringBuffer类。这表示,补充字符表示为一个双字符值,第一个代码单元范围(\ ud800 - \ udbff),第二代码单元围(\ udc00 - \ udfff)。
下面看一下例子:

//1D306是一个辅助平面字符  char[] c = Character.toChars(Integer.parseInt("1D306", 16));String str = new String(c);  System.out.println(str.length());//2  System.out.println(str.codePointCount(0, str.length()));//1  

当字符串中出现辅助字符的时候,获取字符的个数需要使用codePointCount()函数。使用length()函数将会出现错误。

原创粉丝点击