Java实现Unicode编码和解码(\uXXXX)

Java实现Unicode编码和解码(\uXXXX)

摘要

Java实现Unicode编码和解码(\uXXXX)

java实现Unicode转义

package testmain;

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


public class Test_01 {

    public static void main(String[] args) {

        String abc = "\\u2730 8 HOURS \\u2730 Best Fireplace HD 1080p video \\u2730 Relaxing fireplace sound \\u2730 Full HD";

        System.out.println(unicodeToStr(abc));
        System.out.println(getUnicode(unicodeToStr(abc)));

    }


    public static String getUnicode(String s) {
        StringBuilder sb = new StringBuilder(s.length() * 3);
        for (char c : s.toCharArray()) {
            if (c < 256) {
                sb.append(c);
            } else {
                sb.append("\\u");
                sb.append(Character.forDigit((c >>> 12) & 0xf, 16));
                sb.append(Character.forDigit((c >>> 8) & 0xf, 16));
                sb.append(Character.forDigit((c >>> 4) & 0xf, 16));
                sb.append(Character.forDigit((c) & 0xf, 16));
            }
        }
        return sb.toString();
    }

    static final Pattern reUnicode = Pattern.compile("\\\\u([0-9a-zA-Z]{4})");
    public static String unicodeToStr(String s) {
        Matcher m = reUnicode.matcher(s);
        StringBuffer sb = new StringBuffer(s.length());
        while (m.find()) {
            m.appendReplacement(sb,
                    Character.toString((char) Integer.parseInt(m.group(1), 16)));
        }
        m.appendTail(sb);
        return sb.toString();
    }


}

输出结果

✰ 8 HOURS ✰ Best Fireplace HD 1080p video ✰ Relaxing fireplace sound ✰ Full HD
\u2730 8 HOURS \u2730 Best Fireplace HD 1080p video \u2730 Relaxing fireplace sound \u2730 Full HD