unicode和中文互转

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

 

posted @ 2020-09-15 10:18  凉城  阅读(649)  评论(0编辑  收藏  举报