2019獨角獸企業重金招聘Python工程師標準>>>
從一段API描述談起: 在String的length的API中描述是這樣的!
lengthpublic int length()
Returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string.Specified by:
length in interface CharSequenceReturns:
the length of the sequence of characters represented by this object.
其中有一句話:
The length is equal to the number of 16-bit Unicode characters in the string.
直譯過來就是: length的大小和 16 bit 的Unicode字符的個數相同!
1、為什么是16bit?
Unicode是包括目前世界上幾乎所有語言的字符集,每一個字符對應的一個唯一編號,這個編號規則是:常用的Unicode稱謂:BMP,包含了大量的字符集,目前Unicode版本是8.0,BMP是U+0000-U+FFFF代表的字符集。當然了后期又擴展了很多。
可以看到BMP在U+0000-U+FFFF之間的字符,每一個字符的Unicode編碼對應的是四個16進制,每個16進制用四個bit表示,所以一個Unicode就是16 bit。
所以BMP內的字符都是由16Bit組成,所以有多少個16bit就有多少個字符。
[Unicode BMP](https://en.wikipedia.org/wiki/Plane_(Unicode) Unicode和UTF-8對應關系
2、String API codePoint什么意思?
每一個16bit的Unicode就是一個codePoint
關于code point、code unit的對應關系:
wikipedia關于code_point
3、code unit是個什么概念?
The code unit size is equivalent to the bit measurement for the particular encoding:
A code unit in US-ASCII consists of 7 bits; A code unit in UTF-8, EBCDIC and GB18030 consists of 8 bits; A code unit in UTF-16 consists of 16 bits; A code unit in UTF-32 consists of 32 bits. 翻譯: 在US-ASCII中一個code unit代表7bits 在UTF-8,EBCDIC和GB18080中一個code unit代表8bits 在UTF-16中一個code unit代表16bits 在UTF-32中一個code unit代表32bits
總結:
code point是從unicode上定義的概念,是指一個字符集比如A代表的16bits。也就是字符的個數。
比如:
String s = "π王A23";//π用Unicode代表一個16bit的code point//王用Unicode代表一個16bit的code point//A用Unicode代表一個16bit的code point//2用Unicode代表一個16bit的code point//3用Unicode代表一個16bit的code pointSystem.out.println("字符串s的長度為:"+s.length());System.out.println("第三個code point為:"+s.codePointAt(2));
輸出:
字符串s的長度為:5
第三個code point為:65
其中5代表5geunicode字符,每個字符是一個16bit的unicode。 65是代表字母A的標示。是第三個字符A
關于unicode學習最好的方式就是參考Wikipedia中的講述