问题
So I have something like this:
char cr = "9783815820865".charAt(0);
System.out.println(cr); //prints out 9
If I do this:
int cr = "9783815820865".charAt(0);
System.out.println(cr); //prints out 57
I understand that the conversion between char and int is not simply from '9'
to 9
. My problem is right now I simply need to keep the 9 as the int value, not 57. How to get the value 9 instead of 57 as a int
type?
回答1:
You can try with:
int cr = "9783815820865".charAt(0) - '0';
charAt(0)
will return '9'
(as a char
), which is a numeric type. From this value we'll just subtract the value of '0'
, which is again numeric and is exactly nine entries behind the entry of the '9'
character in the ASCII table.
So, behind the scenes, the the subtraction will work with the ASCII codes of '9'
and '0'
, which means that 57 - 48
will be calculated.
回答2:
try this:
char c = "9783815820865".charAt(0);
int cr = Integer.parseInt(c+"");
回答3:
Using Character#getNumericValue may be more idiomatic. Bear in mind that it'll convert anything above 'A'
as 10.
int cr = Character.getNumericValue("9783815820865".charAt(0));
System.out.println(cr);
来源:https://stackoverflow.com/questions/32051600/char-to-int-conversion