Java实现Unicode编码和中文互转

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

幸福因与人分享而更加完美

  • 7
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值