java unicode 转中文(学习用)
第一种方式自己实现(笨,但可以知道原理)
/**
* unicode 转中文
* @param str
* @return
*/
public static String ascii2Native(String str) {
StringBuilder sb = new StringBuilder();
int begin = 0;
int index = str.indexOf("\\u");
while (index != -1) {
sb.append(str.substring(begin, index));
sb.append(ascii2Char(str.substring(index, index + 6)));
begin = index + 6;
index = str.indexOf("\\u", begin);
}
sb.append(str.substring(begin));
return sb.toString();
}
/**
* unicode 转字符
* @param str
* @return
*/
private static char ascii2Char(String str) {
if (str.length() != 6) {
throw new IllegalArgumentException( "参数有误!");
}
if (!"\\u".equals(str.substring(0, 2))) {
throw new IllegalArgumentException("参数有误");
}
String tmp = str.substring(2, 4);
int code = Integer.parseInt(tmp, 16) << 8;
tmp = str.substring(4, 6);
code += Integer.parseInt(tmp, 16);
return (char) code;
}
第二种方式(推荐)
org.apache.commons.lang3.StringEscapeUtils.unescapeJava(yourstr) 有现成的就用现成的,效率高
结论:一定要多看源码,多使用现成的工具类。