Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get char value in java

How can I get the UTF8 code of a char in Java ? I have the char 'a' and I want the value 97 I have the char 'é' and I want the value 233

here is a table for more values

I tried Character.getNumericValue(a) but for a it gives me 10 and not 97, any idea why?

This seems very basic but any help would be appreciated!

like image 865
Nick Avatar asked Dec 01 '10 21:12

Nick


People also ask

How do you find the char value?

If char variable contains int value, we can get the int value by calling Character. getNumericValue(char) method. Alternatively, we can use String. valueOf(char) method.

How do you fetch a character in Java?

To access character of a string in Java, use the charAt() method. The position is to be added as the parameter. String str = "laptop"; Let's find the character at the 4th position using charAt() method.

Can you use == for char in Java?

Yes, char is just like any other primitive type, you can just compare them by == .


2 Answers

char is actually a numeric type containing the unicode value (UTF-16, to be exact - you need two chars to represent characters outside the BMP) of the character. You can do everything with it that you can do with an int.

Character.getNumericValue() tries to interpret the character as a digit.

like image 192
Michael Borgwardt Avatar answered Sep 28 '22 12:09

Michael Borgwardt


You can use the codePointAt(int index) method of java.lang.String for that. Here's an example:

"a".codePointAt(0) --> 97
"é".codePointAt(0) --> 233

If you want to avoid creating strings unnecessarily, the following works as well and can be used for char arrays:

Character.codePointAt(new char[] {'a'},0)
like image 35
Kaitsu Avatar answered Sep 28 '22 11:09

Kaitsu