Core Java (八) Java中的代碼點與代碼單元

來源:互聯網
上載者:User

最近看core java,之前一直不明白,看了不少文章和部落格,總算搞明白了。

Java中,char[]、String、StringBuilder和StringBuffer類中採用了UTF-16編碼,使用U+0000~U+FFFF來表示一個基底字元(BMP字元),但是位於U+D800到U+DBFF和U+DC00到U+DFFF的char被視為無定義字元。大多數的常用Unicode字元使用一個代碼單元就可以表示,而輔助字元需要一對代碼單元表示。即:基底字元用一個char表示,輔助字元使用一對char表示。

Java使用代碼點(Unicode code pointer)這個概念來表示範圍在U+0000與U+10FFFF之間的字元值(int型),代碼單元(Unicode code unit)表示作為UTF-16編碼的代碼單元的 16位char值(char型)。也就是說,可能存在一個字元,它的代碼點數量是1,而代碼單元數量是2。所以,代碼單元的數量並不一定是字元的數量。

相比之下,代碼單元更加偏底層。

相關函數:

length()函數返回採用UTF-16編碼標識的給定字串所需要的代碼單元的數量。

codePointCount()函數返回採用UTF-16編碼標識的給定字串所需要的代碼點的數量。

測試程式:

package com.xujin;public class Test{public static void main(String...args){char[] ch = Character.toChars(0x10400);        System.out.printf("U+10400 高代理字元: %04x\n", (int)ch[0]);//d801        System.out.printf("U+10400 低代理字元: %04x\n", (int)ch[1]);//dc00           String str = new String(ch);        System.out.println("代碼單元長度: " + str.length());//2        System.out.println("代碼點數量: " + str.codePointCount(0, str.length()));//1System.out.println(str.codePointAt(0));//返回給定位置開始或結束的代碼點,66560System.out.println(str.charAt(1));//返回給定位置的代碼單元,由於未定義,返回?//遍曆一個字串,列印出所有字元的代碼點str += "Hello,world!";int i = 0;int cp = str.codePointAt(i);while(i < str.length()){System.out.println(str.codePointAt(i));if(Character.isSupplementaryCodePoint(cp))i += 2;//如果cp所在的位置是代碼點的第一部分,執行此處else i++;}/* * 66560  * 72  * 108  * 111  * 119  * 114  * 100 */}}

參考資料:

http://bbs.csdn.net/topics/340195349

http://blog.csdn.net/longyulu/article/details/7374862

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.