Java: parse int value from a char

Noya picture Noya · Feb 11, 2011 · Viewed 546.7k times · Source

I just want to know if there's a better solution to parse a number from a character in a string (assuming that we know that the character at index n is a number).

String element = "el5";
String s;
s = ""+element.charAt(2);
int x = Integer.parseInt(s);

//result: x = 5

(useless to say that it's just an example)

Answer

Bart Kiers picture Bart Kiers · Feb 11, 2011

Try Character.getNumericValue(char).

String element = "el5";
int x = Character.getNumericValue(element.charAt(2));
System.out.println("x=" + x);

produces:

x=5

The nice thing about getNumericValue(char) is that it also works with strings like "el٥" and "el५" where ٥ and are the digits 5 in Eastern Arabic and Hindi/Sanskrit respectively.