Java.lang.Character.toChars() 方法
描述
java.lang.Character.toChars(int codePoint, char[] dst, int dstIndex) 将指定字符(Unicode 代码点)转换为其 UTF-16 表示形式。
如果指定的code point是BMP(Basic Multilingual Plane or Plane 0)值,同样的值存储在dst[dstIndex]中,返回1。
如果指定的码位是增补字符,则将其代理值存储在dst[dstIndex](高代理)和dst[dstIndex+1](低代理)中,返回2。
声明
以下是 java.lang.Character.toChars() 方法的声明。
public static int toChars(int codePoint, char[] dst, int dstIndex)
参数
codePoint − 一个 Unicode 代码点
dst − 一个 char 数组,其中存储了 codePoint 的 UTF-16 值
dstIndex − 存储转换值的 dst 数组的起始索引
返回值
如果代码点是 BMP 代码点,此方法返回 1,如果代码点是补充代码点,则返回 2。
异常
IllegalArgumentException − 如果指定的 codePoint 不是有效的 Unicode 代码点
NullPointerException - 如果指定的 dst 为 null
IllegalArgumentException - 如果 dstIndex 为负数或不小于 dst.length,或者如果 dstIndex 处的 dst 没有足够的数组元素来存储结果 char 值 )。 (如果 dstIndex 等于 dst.length-1 并且指定的 codePoint 是补充字符,则高代理值不存储在 dst[dstIndex] 中。)
示例
下面的例子展示了 lang.Character.toChars() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class CharacterDemo {
public static void main(String[] args) {
// create an int primitive cp and assign value
int cp = 0x0036;
// create an int primitive res
int res;
/**
* create a char array dst and assign UTF-16 value of cp
* to it using toChars method
*/
char dst[] = Character.toChars(cp);
// check if cp is BMP or supplementary code point using toChars
res = Character.toChars(cp, dst, 0);
String str1 = "It is a BMP code point";
String str2 = "It is a is a supplementary code point";
// print res value
if ( res == 1 ) {
System.out.println( str1 );
} else if ( res == 2 ) {
System.out.println( str2 );
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
It is a BMP code point

