您的位置:首页 > 编程语言 > Java开发

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

2015-06-22 21:42 525 查看
// 将中文转换为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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: