Java中Unicode编码和汉字之间的转换

来源:互联网 发布:ubuntu网络连接不上 编辑:程序博客网 时间:2024/05/16 08:32
// 将中文转换为Unicode编码
public static String stringToUnicode(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
if (ch > 255)
// toHexString() 方法返回为无符号整数基数为16的整数参数的字符串表示形式
str += "\\u" + Integer.toHexString(ch);
else
str += "\\" + Integer.toHexString(ch);
}
return str;
}


// 完成Unicode转换为字符串
public static String unicodeToString(String str) {
// 关于"(\\\\u(\\p{XDigit}{4}))$/"中\\\\第一个和第三个表示转义;
// "(\\\\u(\\p{XDigit}{4}))$/"也可以写成"(/u(\\p{XDigit}{4}))$/"
Pattern pattern = Pattern.compile("(/u(\\p{XDigit}{4}))$/");


Matcher matcher = pattern.matcher(str);


char ch;


while (matcher.find()) {


ch = (char) Integer.parseInt(matcher.group(2), 16);


str = str.replace(matcher.group(1), ch + "");


}


return str;


}
0 0