问题描述
所以我有这样的:
char cr = "9783815820865".charAt(0);
System.out.println(cr); //prints out 9
如果我这样做:
int cr = "9783815820865".charAt(0);
System.out.println(cr); //prints out 57
我理解char和int之间的转换不是简单地从'9'
到 9
。我的问题是现在我只需要保持9作为int值,而不是57.如何获取值9而不是57作为 int
类型?
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?
推荐答案
您可以尝试:
int cr = "9783815820865".charAt(0) - '0';
charAt(0)
c $ c>'9'(作为 char
),它是一个数字类型。从这个值,我们只是减去'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.
因此,在幕后,减法将使用'9'
和'0'
,这意味着将计算 57 - 48
。
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.
这篇关于char到int转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!