【问题标题】:How can I convert a char to int in Java? [duplicate]如何在 Java 中将 char 转换为 int? [复制]
【发布时间】:2018-03-02 18:54:09
【问题描述】:

(我是 Java 编程新手)

例如:

char x = '9';

我需要得到撇号中的数字,即数字 9 本身。 我尝试执行以下操作,

char x = 9;
int y = (int)(x);

但是没有用。

那么我应该怎么做才能得到撇号中的数字呢?

【问题讨论】:

    标签: java char type-conversion int


    【解决方案1】:

    ASCII 表的排列使得字符'9' 的值比'0' 的值大9;字符'8'的值比'0'的值大8;等等。

    所以你可以通过减去'0'得到一个十进制数字char的int值。

    char x = '9';
    int y = x - '0'; // gives the int value 9
    

    【讨论】:

    • @HaimLvov:详细说明...看看在线任何地方的 ASCII 表。任何char 在该表中都有其等效十进制值的数值。因此,您可以从任何其他中减去任何一个以获得数字结果。很自然地,字符 0 到 9 是按顺序排列的,所以数学很有效。
    • @David - 这个答案在性能方面比 Character.getNumericValue(x) 更好吗?
    • In ASCII '0' = 48, 1='49' 等。在这里找到有关理论的有用解释:beginnersbook.com/2019/04/java-char-to-int-conversion
    【解决方案2】:

    你有char '9',它会存储它的ASCII码,所以要获得int值,你有两种方法

    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,如上所示

    【讨论】:

      【解决方案3】:

      如果要获取字符的 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'),我们将它转​​换为一个整数。打印这个整数会给我们 'a' 的 ASCII 值。

      【讨论】:

      • OP 不想获取 ASCII 值,他想在将此字符解释为实际数字时获取该值。对于“9”,他想返回 9 而不是 57(“9”的 ASCII 值)
      【解决方案4】:

      您可以使用 Character 类中的静态方法从 char 中获取数值。

      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);
      }
      

      【讨论】:

        猜你喜欢
        • 2013-01-10
        • 1970-01-01
        • 2017-12-11
        • 2013-08-01
        • 2014-05-02
        • 2016-02-20
        • 2012-07-06
        • 1970-01-01
        相关资源
        最近更新 更多