簡體   English   中英

java從unicode代碼點獲取unicode表示字符串

[英]java get unicode representation string from unicode codepoint

我想從整數代碼點獲取 java 使用的字符串表示形式\\u\u003c/code> 。 我找遍了整個地方,還沒有找到\?\?的工作 awnswer,它是 🦂 。 我通過從字節碼查看器編譯和反編譯 jar 得到了符號。 我不知道它是如何獲取這些字符串的或從哪里獲取的。 在 java 中開發復制 unicode 字符然后粘貼它並獲取它的 java 字符串版本時非常有用。 因此,不必每個類都使用它的 utf-8 格式。

🦂 ( SCORPION ) 是 Unicode Code Point 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

在這里,您可以將字符串中的 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));
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM