code point & code unit

Unicode

是世界通用的字符編碼標準。它包括字符集(包含來自世界各國各地的語言、文字)和編碼方案(將每個字符唯一映射到一個二進制編碼);比如:總共有 A-Z[字符集] 26個字符,使用0-25來進行編碼,即A-0,B-1...[映射關系]。
  這樣以后,0-25每個編碼都是一個code point,即碼字;如何將這些碼字在計算機中表示?[這里我們只是一個很簡單的例子,現(xiàn)實中的字符集數(shù)量遠遠大于26,可能需要多個字節(jié)序列才能表示。因此就存在在計算機中如何表示的問題]。根據(jù)表示方法的不同,又區(qū)分為我們常見的UTF-8、UTF-16和UTF-32編碼方式。

  • UTF-8:使用變長的字節(jié)序列來表示字符;某個字符(對應一個code point)可能使用1-4個字節(jié)才能表示;這樣1個字節(jié)就是一個code unit,即代碼單元。代表最小的可用來識別一個合法字符的最小字節(jié)數(shù);即一個code point可能由1-4個code unit組成,code unit為一個字節(jié)
  • UTF-16:使用變長字節(jié)序列來表示字符;某個字符(對應一個code point)可能使用2個或者4個字符來表示;這樣2個字節(jié)就是一個code unit;因為2個字節(jié)序列是最小的能夠識別一個code point的單位;即一個code point可能由1-2個code unit組成,code unit為2個字節(jié);
  • UTF-32:定長的4個字節(jié)表示一個字符;一個code point對應一個4字節(jié)的序列,這樣4個字符數(shù)就是一個code unit。即一個code point由1個code unit組成,code unit為4個字節(jié);

A Unicode code unit is a bit size used by a particular Unicode encoding.For example UTF-8 has a code unit size of 8 bits and UTF-16 has 16 and UTF-32 has 32.To represent a character (i.e. a code point, which is a Unique integer assigned to each character) one or many code units may be required depending on the encoding.Java uses UTF-16 and this means the code unit size is 16 bits. Unicode has over 1 million code points (10FFFF+1 in hex). 16 bits can represents only FFFF+1 code points. (This range is called the BMP (Basic Multilingual Plane. It contains all the commonly used character in the world and some more).So to represent code points outside the BMP the UTF-16 encoding specifies surrogate pairs. For this two special ranges are defined within the BMP. In UTF-16 any character outside the BMP is represented by two 16 bit code units in this range. (In fact surrogate characters are defined only for UTF-16). Now it should be clear that certain characters may require two code units in UTF-16.So counting 16 bit code units will not yield the correct "length of characters". String.length() returns the number of code units in the String.Since 1.5 you can use codePointCount(int beginIndex, int endIndex) to get the length of the characters. It will count a surrogate pair as one character.

Java中的String類

Java JVM中的String類使用的是UTF-16編碼方式。
String.length():方法返回的是字符串中char的字符個數(shù);注意每個字符為2字節(jié)長度。
String.codePointCount():方法返回字符串中的碼字個數(shù)。一個碼字即對應一個Unicode字符??赡転?個字節(jié)長度或者4字節(jié)長度的。
以上兩個方法的返回值可能是不相等的。如果字符串中僅包含基本多語言平面(BMP)的Unicode字符,則兩者值相等。否則code point count值是小于length的,因為一個不是BMP的字符,需要兩個char(一個代理對,包括前導代理和后尾代理構成)來表示。

char String.charAt(index):方法返回index位置的字符,注意該index取值是基于length方法的。
int String.codePointAt(index):方法返回index位置的碼字。
以上兩個方法一個返回char,一個返回int,兩者可能是不相同的。也是因為超出BMP范圍的字符需要兩個char來表示。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容