Java中unicode增补字符(辅助平面)相关用法简介

转载自 http://blog.csdn.net/gjb724332682/article/details/51324036

前言

Java从1.5版本开始,加入了unicode辅助平面的支持。相关的API主要在Character和String类里。增补字符是用一个长度为2的char数组表示的,分别表示高代理项和低代理项。用法可以参考如下的例子。

例一

codePointAt方法的源码如下:

public static int codePointAt(char[] a, int index) {  
    return codePointAtImpl(a, index, a.length);  
}  
static int codePointAtImpl(char[] a, int index, int limit) {  
        char c1 = a[index++];  
        if (isHighSurrogate(c1)) {  
            if (index < limit) {  
                char c2 = a[index];  
                if (isLowSurrogate(c2)) {  
                    return toCodePoint(c1, c2);  
                }  
            }  
        }  
        return c1;  
    }
public static int toCodePoint(char high, char low) {  
        return ((high - 'uD800') << 10)  
            + (low - 'uDC00') + 65536;  
    }  

如果是输入增补字符数组,那么,当传入索引是0的时候,就会返回整个增补字符的码点,当传入索引是1的时候,就会返回增补字符数组中第二个字符的码点。

public static void main(String[] args) {  
        char[] c = Character.toChars(Integer.parseInt("1D306", 16));//1D306是一个辅助平面字符  
        System.out.println(Character.codePointAt(c, 0));//输出119558,这个是1D306对应的10进制值  
        System.out.println(Character.codePointAt(c, 1));//输出57094,这个是c[1]对应字符的10进制值  
    }  

当传入的字符数组是都是基本平面的字符时,直接返回传入的索引对应的基本平面字符的码点。

public static void main(String[] args) {  
        char[] c = {'a', 'b', '测', '试'};  
        System.out.println(Character.codePointAt(c, 0));//97  
        System.out.println(Character.codePointAt(c, 1));//98  
        System.out.println(Character.codePointAt(c, 2));//27979  
        System.out.println(Character.codePointAt(c, 3));//35797  
        System.out.println((char) 97);//a  
        System.out.println((char) 98);//b  
        System.out.println((char) 27979);//
        System.out.println((char) 35797);//
    }  

例二

String类的length和codePointCount方法,在处理增补字符时,返回的数据是不一样的,而对于基本平面来说,返回值都是一样的。
length返回字符串长度,codePointCount返回代码点数量。
public static void main(String[] args) {  
        char[] c = Character.toChars(Integer.parseInt("1D306", 16));//1D306是一个辅助平面字符  
        System.out.println(Character.codePointAt(c, 0));//输出119558,这个是1D306对应的10进制值  
        System.out.println(Character.codePointAt(c, 1));//输出57094,这个是c[1]对应字符的10进制值  
        System.out.println(new String(c).codePointAt(0));//输出119558,这个是1D306对应的10进制值  
        System.out.println(new String(c).codePointAt(1));//输出57094,这个是c[1]对应字符的10进制值  
        String str = "abcdefg" + new String(c);  
        System.out.println(str.length());//9  
        System.out.println(str.codePointCount(0, str.length()));//8  
    }  

上面的例子,字符串长度是9,因为字符U+1D306需要一个长度为2的字符数组来表示,而实际上代码点只有1个,所以会分别返回9和8。

 
原文地址:https://www.cnblogs.com/liujinhong/p/6498885.html