Java实现Unicode和中文相互转换

发布时间 2023-04-27 17:25:59作者: kelelipeng

 

Java中Unicode和中文相互转换
1. 什么是Unicode编码?
2. 中文加密[中文字符 -> Unicode字符]
3. Unicode解码[Unicode字符 -> 中文字符]
4. 测试案例
1. 什么是Unicode编码?
快速了解什么是Unicode

 

2. 中文加密[中文字符 -> Unicode字符] 

/**
     * @Title: unicodeEncode 
     * @Description: unicode编码 将中文字符转换成Unicode字符
     * @param string
     * @return
     */
    public String unicodeEncode(String string) {
        char[] utfBytes = string.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }

 

 


3. Unicode解码[Unicode字符 -> 中文字符] 

    /**
     * @param string
     * @return 转换之后的内容
     * @Title: unicodeDecode
     * @Description: unicode解码 将Unicode的编码转换为中文
     */
    public String unicodeDecode(String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }

 


4. 测试案例 

    public void test(){
        String str = "真香IT";
        // 加密 中文 -> Unicode
        String unicodeEncode = unicodeEncode(str);
        System.out.println(str + " ---> " + unicodeEncode);
        // 解密 Unicode -> 中文
        String zh_str = unicodeDecode(unicodeEncode);
        System.out.println(unicodeEncode + " ---> " + zh_str);
    }

 


 

————————————————
版权声明:本文为CSDN博主「真香IT」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Steven_Start/article/details/124932044