话不多说直接上代码:
/**
* 带中文的字符串转为 /u16进制 的 Unicode 码
*/
private String tfToHex(String str){
Integer.toHexString(0);
//匹配单字符是否中文的正则
String regex = "[\u4e00-\u9fa5]";
char [] arr = str.toCharArray();
StringBuffer newStr = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
char c = arr[i];
if ((c+"").matches(regex)) {
String temp = Integer.toHexString(c);
newStr.append("\\u"+temp);
}else {
newStr.append(c);
}
}
return newStr.toString();
}
测试代码:
public static void main(String[] args) {
System.out.println(new Test2().tfToHex("欢迎查看胡萧徒的-优快云"));
}
输出结果:
\u6b22\u8fce\u67e5\u770b\u80e1\u8427\u5f92\u7684-优快云