我有一个字符串e2 80 99
,它是UTF-8字符的十六进制表示。该字符串代表
U+2019 ’ e2 80 99 RIGHT SINGLE QUOTATION MARK
我想将e2 80 99
转换为其对应的Unicode码点,即U+2019
或甚至'
(单引号)。
我该怎么做?
基本上,您需要获得使用UTF-8编码的字符的字符串表示形式,然后获取生成的字符串的第一个字符(如果生成的字符在UTF-16中表示为两个代理项,则获取第一个和第二个字符)。这是一个概念验证:
public static void main(String[] args) throws Exception {
// Convert your representation of a char into a String object:
String utf8char = "e2 80 99";
String[] strNumbers = utf8char.split(" ");
byte[] rawChars = new byte[strNumbers.length];
int index = 0;
for(String strNumber: strNumbers) {
rawChars[index++] = (byte)(int)Integer.valueOf(strNumber, 16);
}
String utf16Char = new String(rawChars, Charset.forName("UTF-8"));
// get the resulting characters (Java Strings are "encoded" in UTF16)
int codePoint = utf16Char.charAt(0);
if(Character.isSurrogate(utf16Char.charAt(0))) {
codePoint = Character.toCodePoint(utf16Char.charAt(0), utf16Char.charAt(1));
}
System.out.println("code point: " + Integer.toHexString(codePoint));
}