Java实现Unicode和中文相互转换

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);
    }

测试  

————————————————
转载于:https://blog.csdn.net/Steven_Start/article/details/124932044

猜你喜欢

转载自blog.csdn.net/weixin_42602900/article/details/128644880