nick zoum nick zoum - 1 month ago 8
Java Question

Java get Compact Description of a Character

Is there any way to get the

Compact Description
of a
Character
/
char
in
Java 8
?

For example the code shown below:

System.out.println(getDescription(' '));
System.out.println(getDescription(' '));
System.out.println(getDescription((char)13));
System.out.println(getDescription((char)10));


Should Output:

Space
Tab
Enter
Line Feed


I know I could do this by creating a
map
and store each special
Character
and their respective
Description
, but I was wondering if there already is a
function
that does this.

Update



I was just informed by this answer that you could use the
getName()
method, and this is very close to what I am looking for it is not very convenient since, the returned String is too large.

I am creating an app that uses macros, and I want to show in my GUI the name of the key, so writing
LATIN CAPITAL LETTER A
is not very convenient.

I suppose, I could remove the words
LATIN CAPITAL LETTER
instructed by Eli Sadoff but that would only work for latin characters, so I would also have to remove all the words that describe the rest of the alphabets, and I'm not sure how to do that.

(I could obviously very easily differentiate bettwen
A
and
a
by checking if the output contains
CAPITAL
or
SMALL
so that is no issue).

Essentially I would want the result to look like this.

Answer

You want to use the static method Character.getName(int). This method returns the Unicode name for the specified code point. For your examples it would return

Character.getName(' '); #=> "SPACE"
Character.getName('\t'); #=> "CHARACTER TABULATION"
Character.getName(10); #=> "LINE FEED (LF)"
Character.getName(13); #=> "CARRIAGE RETURN (CR)"

The full documentation of the method is here.

Here is how this was implemented by the author:

public static String getDescription(char ch) {
    String description = Character.getName(ch);
    description = description == null ? null : capitalizeFully(description);
    boolean flag = isPrintableChar(ch) && !Character.isWhitespace(ch);
    return flag ? Character.toString(ch) : description;
}

public static String capitalizeFully(String text) {
    String[] words = text.split(" ");
    StringBuilder string = new StringBuilder();
    for (int index = 0; index < words.length; index++) {
        String temp = words[index].toLowerCase();
        boolean flag = temp.length() == 1;
        char first = temp.charAt(0);
        string.append(index == 0 ? "" : " ");
        string.append(Character.toUpperCase(first));
        string.append(flag ? "" : temp.substring(1));
    }
    return string.toString();
}

public static boolean isPrintableChar(char c) {
    Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
    return (!Character.isISOControl(c)) && c != KeyEvent.CHAR_UNDEFINED && block != null
            && block != Character.UnicodeBlock.SPECIALS;
}