java从unicode代码点获取unicode表示字符串

wf82jlnq  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(376)

我想得到字符串表示 \u java从整数代码点开始使用。我找遍了所有的地方,还没有找到一个合适的工作地点 \ud83e\udd82 那是🦂 . 我从字节码查看器编译和反编译jar得到了这个符号。我不知道这些弦是怎么来的,也不知道从哪里来的。在java中,复制一个unicode字符,然后将其粘贴进去,并获得它的java字符串版本,这是非常有用的。因此,不必每个类都使用utf-8。

vh0rcniy

vh0rcniy1#

🦂 (scorpion)是unicode代码点 1f982 ,即utf-16 d83e dd82 ,和utf-8 f0 9f a6 82 .
要将代码点整数转换为unicode转义java字符串,请运行以下代码:

// Java 11+
int codePoint = 0x1f982;
char[] charArray = Character.toString(codePoint).toCharArray();
System.out.printf("\\u%04x\\u%04x", (int) charArray[0], (int) charArray[1]);
// prints: \ud83e\udd82
// Java 1.5+
int codePoint = 0x1f982;
char[] charArray = new String(new int[] { codePoint }, 0, 1).toCharArray();
System.out.printf("\\u%04x\\u%04x", (int) charArray[0], (int) charArray[1]);
// prints: \ud83e\udd82
1aaf6o9v

1aaf6o9v2#

在这里,您可以将unicode字符从字符串直接转换为java格式。

/**
     * return the java unicode string from the utf-8 string
     * TODO: add an option to change the unicode number strings to not just the codepoints
     */
    public static String toUnicodeEsq(String unicode)
    {
        StringBuilder b = new StringBuilder();
        int[] arr = unicode.codePoints().toArray();
        for(int i : arr)
            b.append(toUnicodeEsq(i));
        return b.toString();
    }

    public static String toUnicodeEsq(int cp)
    {
        return isAscii(cp) ? "" + (char) cp : Character.isBmpCodePoint(cp) ? "\\u" + String.format("%04x", cp) : "\\u" + String.format("%04x", (int)Character.highSurrogate(cp)) + "\\u" + String.format("%04x", (int)Character.lowSurrogate(cp) );
    }

    public static boolean isAscii(int cp) 
    {
        return cp <= Byte.MAX_VALUE;
    }

我的方法不直接支持unicode数字(u+hex),但是,您可以从css、html和unicode数字格式中逐个获取字符串

/**
     * get the codepoint from the unicode number. from there you can convert it to a unicode escape sequence using {@link JavaUtil#getUnicodeEsq(int)}
     * "U+hex" for unicode number
     * "&#codePoint;" or "&#hex;" for html
     * "\hex" for css
     * "hex" for lazyness
     */
    public static int parseUnicodeNumber(String num)
    {
        num = num.toLowerCase();
        if(num.startsWith("u+"))
            num = num.substring(2);
        else if(num.startsWith("&#"))
            return num.startsWith("&#x") ? Integer.parseInt(num.substring(3, num.length() - 1), 16) : Integer.parseInt(num.substring(2, num.length() - 1)); 
        else if(num.startsWith("\\"))
            num = num.substring(1);
        return Integer.parseInt(num, 16);
    }

    /**
     * convert a unicode number directly to unicode escape sequence in java
     */
    public static String unicodeNumberToEsq(String num)
    {
        return toUnicodeEsq(parseUnicodeNumber(num));
    }

相关问题