Unicode 编码解码工具类

 /**
     * 字符串转 Unicode 编码(标准格式 \\uXXXX)
     */


public static String stringToUnicode(String str) { if (str == null || str.isEmpty()) { return ""; } StringBuilder unicode = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); // 对非ASCII字符进行编码 if (ch > 127) { unicode.append("\\u").append(String.format("%04x", (int) ch).toUpperCase()); } else { unicode.append(ch); } } return unicode.toString(); }


    /**
     * Unicode 解码为字符串(标准格式 \\uXXXX)
     */
    public static String unicodeToString(String unicodeStr) {
        if (unicodeStr == null || unicodeStr.isEmpty()) {
            return "";
        }
        
        Pattern pattern = Pattern.compile("(\\\\u[0-9a-fA-F]{4})");
        Matcher matcher = pattern.matcher(unicodeStr);
        
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String unicode = matcher.group(1);
            char ch = (char) Integer.parseInt(unicode.substring(2), 16);
            matcher.appendReplacement(sb, String.valueOf(ch));
        }
        matcher.appendTail(sb);
        
        return sb.toString();
    }
posted @ 2025-10-10 11:23  黑狗已醒  阅读(7)  评论(0)    收藏  举报