How to get decimal Unicode character value in Java?

I need a programmatic way to get the decimal value of each character in a String so that I can encode them as HTML objects, for example:

UTF-8:

著者名

Decimal:

著者名
+5
source share
2 answers

I suspect you are just interested in converting from charto int, which is implicit:

for (int i = 0; i < text.length(); i++)
{
    char c = text.charAt(i);
    int value = c;
    System.out.println(value);
}

EDIT: if you want to handle surrogate pairs, you can use something like:

for (int i = 0; i < text.length(); i++)
{
    int codePoint = text.codePointAt(i);
    // Skip over the second char in a surrogate pair
    if (codePoint > 0xffff)
    {
        i++;
    }
    System.out.println(codePoint);
}
+11
source

Having read John's post well and still thinking about Java surrogates, I decided to be a little less lazy and google. There actually support for surrogates in the character class is just a little .. circular motion

, , , :

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        if (Character.isHighSurrogate(ch)) {
            System.out.println("Codepoint: " + 
                   Character.toCodePoint(ch, str.charAt(i + 1)));
            i++;
        }
        System.out.println("Codepoint: " + (int)ch);
    }
+2

All Articles