Java实现Unicode编码和中文互转
1.中文字符串转换为Unicode编码
/**
* 中文转Unicode
* 其他英文字母或特殊符号也可进行Unicode编码
* @param cn
* @return
*/
public static String cnToUnicode(String cn) {
char[] chars = cn.toCharArray();
StringBuilder returnStr = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
returnStr.append("\\u").append(Integer.toString(chars[i], 16));
}
return returnStr.toString();;
}
2. Unicode编码转换为中文字符串
/**
* Unicode转 汉字字符串
*
* @param str
* @return
*/
public static String unicodeToCN(String str) {
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;
}
# 测试
public class UnicodeUtils {
public static void main(String[] args) throws UnsupportedEncodingException {
//中文转Unicode编码
String cnStr = "中文转码";
String unicodeResult = cnToUnicode(cnStr);
System.out.println("中文转Unicode编码后结果:" + unicodeResult);
//Unicode编码转中文
//第一种格式
String cnResult = unicodeToCN(unicodeResult);
System.out.println("Unicode编码转中文后结果:" + cnResult);
//第二种格式
String unicodeStr = "{\"status\":0,\"msg\":\"\\u4e2d\\u6587\\u8f6c\\u7801\",\"code\":2}";
String cnResult2 = unicodeToCN(unicodeStr);
System.out.println("Unicode编码转中文后结果:" + cnResult2);
}
}
# 返回结果
中文转Unicode编码后结果:\u4e2d\u6587\u8f6c\u7801
Unicode编码转中文后结果:中文转码
Unicode编码转中文后结果:{"status":0,"msg":"中文转码","code":2}
#总结:
java中的一个char是两个字节,采用unicode字符集,使用指定的编码方式存储在内存中。
参考链接:
https://blog.csdn.net/u013905744/article/details/74452012/
Unicode工具类下载地址:
https://download.csdn.net/download/weixin_45358267/18466972
幸福因与人分享而更加完美