Converting characters to integers in Java(在Java中将字符转换为整数)
问题描述
谁能给我解释一下这里发生了什么:
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中将字符转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在Java中将字符转换为整数


基础教程推荐
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01