How do I get the decimal value of a unicode character in Java?

后端 未结 2 426
耶瑟儿~
耶瑟儿~ 2021-01-18 04:28

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

UTF-8:

2条回答
  •  滥情空心
    2021-01-18 04:49

    I suspect you're just interested in a conversion from char to 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);
    }
    

提交回复
热议问题