Unicode(统一码、万国码、单一码)是一种在计算机上使用的字符编码。它为每种语言中的每个字符设定了统一并且唯一的二进制编码,以满足跨语言、跨平台进行文本转换、处理的要求。
UTF-8(8-bit Unicode Transformation Format)是一种针对Unicode的可变长度字符编码(定长码),也是一种前缀码。它可以用来表示Unicode标准中的任何字符
/**
* 把Unicode编码转换为汉字
*
* @param source
* @return
*/
public static String convertUnicodeToChar(String source) {
if (null == source || " ".equals(source)) {
return source;
}
StringBuffer sb = new StringBuffer();
int i = 0;
while (i < source.length()) {
if (source.charAt(i) == '\\') {
int j = Integer.parseInt(source.substring(i + 2, i + 6), 16);
sb.append((char) j);
i += 6;
} else {
sb.append(source.charAt(i));
i++;
}
}
return sb.toString();
}
/**
* 汉字转换为Unicode编码
*
* @param source
* @return
*/
public static String convertCharToUnicode(String source) {
if (null == source || " ".equals(source)) {
return source;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < source.length(); i++) {
char c = source.charAt(i);
sb.append("\\u" + Integer.toHexString(c));
}
return sb.toString();
}
// 主调方法
public static void main(String[] args) {
System.out.println(convertUnicodeToChar("中国人民:\u666e\u901a\u65e5\u884c\u516c\u4ea4\u8f66"));
System.out.println(convertCharToUnicode("运通路公交车110"));
}
输出结果:
中国人民:普通日行公交车
\u8fd0\u901a\u8def\u516c\u4ea4\u8f66\u31\u31\u30