咸咸海风

https://github.com/xianxianhaifeng

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::
public class YxqTest {
    public static  void main(String[] args){
        // unicode 打印
        String title="\u4F60\u597D";
        System.out.println(title);
        
        // 中文-转-unicode
        String str = "你好";
        System.out.println(cnToUnicode(str));

        // unicode-转-中文
        String title2="\\u4F60\\u597D";
        System.out.println(unicodeToCn(title2));
    }

    private static String unicodeToCn(String unicode) {
        /** 以 \ u 分割,因为java注释也能识别unicode,因此中间加了一个空格*/
        String[] strs = unicode.split("\\\\u");
        String returnStr = "";
        // 由于unicode字符串以 \ u 开头,因此分割出的第一个字符是""。
        for (int i = 1; i < strs.length; i++) {
            returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
        }
        return returnStr;
    }

    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)).toUpperCase();
        }
        return returnStr;
    }
}

输出:

 

 

 

posted on 2019-11-06 10:04  咸咸海风  阅读(280)  评论(0编辑  收藏  举报