我有一个字符串e2 80 99
,它是UTF-8字符的十六进制表示。字符串代表
U+2019 ’ e2 80 99 RIGHT SINGLE QUOTATION MARK
我想将e2 80 99
转换为相应的Unicode代码点U+2019
或'
(单引号)。
我该怎么做?
答案 0 :(得分:3)
基本上你需要获得用utf-8编码的字符的String表示,然后得到结果字符串的第一个字符(如果结果字符表示为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));
}