Creating Unicode character from its number

后端 未结 13 1845
挽巷
挽巷 2020-11-28 21:38

I want to display a Unicode character in Java. If I do this, it works just fine:

String symbol = \"\\u2202\";

symbol is equal to \"∂\". That\'

13条回答
  •  没有蜡笔的小新
    2020-11-28 22:06

    Although this is an old question, there is a very easy way to do this in Java 11 which was released today: you can use a new overload of Character.toString():

    public static String toString​(int codePoint)
    
    Returns a String object representing the specified character (Unicode code point). The result is a string of length 1 or 2, consisting solely of the specified codePoint.
    
    Parameters:
    codePoint - the codePoint to be converted
    
    Returns:
    the string representation of the specified codePoint
    
    Throws:
    IllegalArgumentException - if the specified codePoint is not a valid Unicode code point.
    
    Since:
    11
    

    Since this method supports any Unicode code point, the length of the returned String is not necessarily 1.

    The code needed for the example given in the question is simply:

        int codePoint = '\u2202';
        String s = Character.toString(codePoint); // <<< Requires JDK 11 !!!
        System.out.println(s); // Prints ∂
    

    This approach offers several advantages:

    • It works for any Unicode code point rather than just those that can be handled using a char.
    • It's concise, and it's easy to understand what the code is doing.
    • It returns the value as a string rather than a char[], which is often what you want. The answer posted by McDowell is appropriate if you want the code point returned as char[].

提交回复
热议问题