将字符转换为Java中的整数 [英] Converting characters to integers in Java

查看:217
本文介绍了将字符转换为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?

Edit:是我知道 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: code> 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 值。例如,字符'\\\Ⅼ'(罗马数字五十)将返回值为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 ('\\\A'至'\\\Z'),小写字母('\\\a'通过'\\\z')和全宽变体('\\\A'至'\\\Z'和'\\\a'至'\\\z') 表单具有从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.


此方法返回字符的数字值,作为
非负int值;

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.

a href =http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#getNumericValue%28char%29>此处是链接。

And here is the link.

这篇关于将字符转换为Java中的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆