Java:如何将unicode字符串表情符号转换为Integer

问题描述 投票:-1回答:2

我收到了一个包含表情符号代码的unicode字符串,例如:“U + 1F44F”(来自表情符号表:http://apps.timwhitlock.info/emoji/tables/unicode)。

我想将此字符串转换为Integer,我该怎么做?

我试过这个,但它崩溃了:

int hex = Integer.parseInt(unicodeStr, 16);

多谢你们!

java unicode-string
2个回答
2
投票

@flakes的评论给出了正确的回答。 U +仅表示以下代码点(或十六进制数)是Unicode。要转换为整数的值是代码点,因此必须省略.substring(2)的前两个字符

您将获得以下代码:

int hex = Integer.parseInt(unicodeStr.substring(2), 16);

2
投票

Unicode编号如“字符”,代码点,最多3个字节范围,如U + 1F44F。

Java String有一个带代码点的构造函数。

int[] codepoints = { 0x1F44F };
String s = new String(codepoints, 0, codepoints.length);

public static String fromCodepoints(int... codepoints) {
    return new String(codepoints, 0, codepoints.length);
}

s = fromCodepoints(0x1F44F, 0x102);

Java String包含Unicode作为chars的内部数组。每个字符'(2个字节)都是UTF-16编码的。对于较低范围,char可以是代码点。并且U + 0102可以写成包含char "\u0102"'\u0102'

请注意,表情符号必须可以在字体中表示。

Font font = ...
if (!font.canDisplay(0x1F44F)) {
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.