如何在Java中将char转换为int?
(我是Java编程的新手)
我有例如:
char x = '9';
我需要得到撇号中的数字,数字9本身。 我试着做以下事情,
char x = 9; int y = (int)(x);
但它不起作用。
那么我该怎么做才能得到撇号中的数字呢?
碰巧的是,字符'9'
的ascii / unicode值比'0'
的值大'9'
(类似于其他数字)。
因此,您可以使用减法获取十进制数字char的int值。
char x = '9'; int y = x - '0'; // gives 9
我有char '9'
,它会存储它的ASCII码,所以要获得int值,你有2种方法
char x = '9'; int y = Character.getNumericValue(x); //use a existing function System.out.println(y + " " + (y + 1)); // 9 10
要么
char x = '9'; int y = x - '0'; // substract '0' code to get the difference System.out.println(y + " " + (y + 1)); // 9 10
事实上,这也有效:
char x = 9; System.out.println(">" + x + "<"); //> < prints a horizontal tab int y = (int) x; System.out.println(y + " " + (y + 1)); //9 10
你存储了9
代码,它对应于一个horizontal tab
(你可以看到当打印为String
,你也可以使用它作为int
,如上所示
您可以使用Character类中的静态方法从char获取Numeric值。
char x = '9'; if (Character.isDigit(x)) { // Determines if the specified character is a digit. int y = Character.getNumericValue(x); //Returns the int value that the //specified Unicode character represents. System.out.println(y); }
如果要获取字符的ASCII值,或者只是将其转换为int,则需要从char转换为int。
什么是铸造? 转换是指我们明确地从一个原始数据类型或类转换为另一个。 这是一个简短的例子。
public class char_to_int { public static void main(String args[]) { char myChar = 'a'; int i = (int) myChar; // cast from a char to an int System.out.println ("ASCII value - " + i); }
在这个例子中,我们有一个字符(’a’),我们将它转换为整数。 打印此整数将为我们提供ASCII值’a’。
你可以这样做字符串文字:
int myInt = Integer.parseInt("1234");