格式为:\uxxxx(4个x)
PREFIX_UNICODE = “\u”;
public static String ascii2Native(String str) {
StringBuilder sb = new StringBuilder();
int begin = 0;
int index = str.indexOf(PREFIX_UNICODE);
while (index != -1) {
sb.append(str.substring(begin, index));
sb.append(ascii2Char(str.substring(index, index + 6)));
begin = index + 6;
index = str.indexOf(PREFIX_UNICODE, begin);
}
sb.append(str.substring(begin));
return sb.toString();
}
private static char ascii2Char(String str) {
if (str.length() != 6) {
throw new IllegalArgumentException("Ascii string of a native character must be 6 character.");
}
if (!PREFIX_UNICODE.equals(str.substring(0, 2))) {
throw new IllegalArgumentException("Ascii string of a native character must start with \"\\u\".");
}
String tmp = str.substring(2, 4);
// 将十六进制转为十进制
int code = Integer.parseInt(tmp, 16) << 8; // 转为高位,后与地位相加
tmp = str.substring(4, 6);
code += Integer.parseInt(tmp, 16); // 与低8为相加
return (char) code;
}
直接调用ascii2Native(String str)传入要转的字符串,就会将你字符串中unicode转为汉字!