unicode和中文互转

2022-02-10 14:40:15 浏览数 (1)

代码语言:javascript复制
package com.cdv.nsite;

public class Test {
     
    //Unicode转中文方法
    private static String unicodeToCn(String unicode) {
        String[] strs = unicode.split("\\u");
        String returnStr = "";
        for (int i = 1; i < strs.length; i  ) {
            if(strs[i].length() > 4) {
                returnStr  = (char) Integer.valueOf(strs[i].substring(0,4), 16).intValue();
                System.out.println(strs[i]);
                returnStr  = strs[i].substring(4);
            }else {
                 returnStr  = (char) Integer.valueOf(strs[i], 16).intValue();
            }
           
        }
        return returnStr;
    }
 
    //中文转Unicode
    private static String cnToUnicode(String cn) {
        char[] chars = cn.toCharArray();
        String returnStr = "";
        for (int i = 0; i < chars.length; i  ) {
            returnStr  = "\u"   Integer.toString(chars[i], 16);
        }
        return returnStr;
    }
    //测试
    public static void main(String[] args) {
        //Unicode码
        String aa = "\u672A\u53D1\u73B0\u4F1A\u8BDD\u8BB0\u5F55\uFF0CSSO\u767B\u5F55\u5931\u8D25\uFF01";
        //转中文
        String cnAa = unicodeToCn(aa);
        System.out.println("Unicode转中文结果: " cnAa);//转Unicode
        String unicodeAa = cnToUnicode(cnAa);
        System.out.println("中文转Unicode结果: " unicodeAa);
    }
 
 
}

0 人点赞