問題描述
誰能給我解釋一下這里發生了什么:
Can someone please explain to me what is going on here:
char c = '+';
int i = (int)c;
System.out.println("i: " + i + " ch: " + Character.getNumericValue(c));
這將打印 i: 43 ch:-1
.這是否意味著我必須依靠原始轉換將 char
轉換為 int
?那么如何將 Character
轉換為 Integer
?
This prints i: 43 ch:-1
. Does that mean I have to rely on primitive conversions to convert char
to int
? So how can I convert a Character
to Integer
?
是的,我知道如果 Character.getNumericValue
不是數值,那么它會返回 -1
,這對我來說很有意義.問題是:為什么進行原始轉換會返回 43
?
Yes I know Character.getNumericValue
returns -1
if it is not a numeric value and that makes sense to me. The question is: why does doing primitive conversions return 43
?
Edit2: 43
是 +
的 ASCII,但我希望轉換不會像 getNumericValue代碼> 沒有成功.否則這意味著有兩種語義等效的方式來執行相同的操作但結果不同?
43
is the ASCII for +
, but I would expect the cast to not succeed just like getNumericValue
did not succeed. Otherwise that means there are two semantic equivalent ways to perform the same operation but with different results?
推薦答案
Character.getNumericValue(c)
java.lang.Character.getNumericValue(char ch)
返回指定 Unicode 字符所代表的 int
值.例如,字符 'u216C'
(羅馬數字 50)將返回一個值為 50 的 int.
The java.lang.Character.getNumericValue(char ch)
returns the int
value that the specified Unicode character represents. For example, the character 'u216C'
(the roman numeral fifty) will return an int with a value of 50.
字母 AZ 大寫 ('u0041' 到 'u005A')
、小寫 ('u0061' 到 'u007A')
和完整寬度變體 ('uFF21' 到 'uFF3A' 和 'uFF41' 到 'uFF5A')
形式的數值從 10 到 35.這與 Unicode 規范無關,它不為這些 char 值分配數值.
The letters A-Z in their uppercase ('u0041' through 'u005A')
, lowercase ('u0061' through 'u007A')
, and full width variant ('uFF21' through 'uFF3A' and 'uFF41' through 'uFF5A')
forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.
此方法返回字符的數值,作為非負整數值;
This method returns the numeric value of the character, as a nonnegative int value;
-2 如果字符的數值不是非負整數;
-2 if the character has a numeric value that is not a nonnegative integer;
-1 如果字符沒有數值.
-1 if the character has no numeric value.
這里是鏈接.
這篇關于在Java中將字符轉換為整數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!