阅读 116

中文字符串互转UniCode(含JS中转UniCode)


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UniCodeUtil {

    // 中文字符串转UniCode
    public static String getUNStr(String cnStr) {
        char[] utfBytes = cnStr.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;
    }

    // JS写法:
    // 中文转为Unicode
    // toUnicode : function(s) {
    // return s.replace(/([\u4E00-\u9FA5]|[\uFE30-\uFFA0])/g, function(newStr) {
    // return "\\u" + newStr.charCodeAt(0).toString(16);
    // });

    // unicode转换为中文
    public static String getCNStr(String unStr) {
        if (unStr == null || unStr.length() == 0)
            return "";
        try {
            String unicodeCompile = "(?<=\\\\u).{4}?";
            String a;
            Matcher matcher = Pattern.compile(unicodeCompile).matcher(unStr);
            for (; matcher.find();) {
                a = matcher.group();
                String ch = String.valueOf((char) Integer.valueOf(a, 16)
                        .intValue());
                unStr = unStr.replace("\\u" + a, ch);
            }
            return unStr;
        } catch (Exception e) {
            return unStr;
        }
    }
}

原文:https://www.cnblogs.com/Pro-Cyon/p/14907675.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐