繁体   English   中英

在使用charAt的java中的atoi

[英]atoi in java using charAt

我知道这样做的一个解决方案如下:

 String tmp = "12345";
      int result = 0;
      for (int i =0; i < tmp.length(); i++){
          char digit = (char)(tmp.charAt(i) - '0');
          result += (digit * Math.pow(10, (tmp.length() - i - 1)));

      }

      System.out.println(result);

我不明白的原因是:

char digit = (char)(tmp.charAt(i) - '0');

怎么能转换成数字?

char digit =(char)(tmp.charAt(i) - '0');

ascii表中 ,从'0''9'字符是连续的。 因此,如果您知道tmp.charAt(i)将返回09之间的字符,则减去0将从零返回偏移量,即该字符表示的数字。

使用Math.pow是非常昂贵的,你最好使用Integer.parseInt。

您不必使用Math.pow。 如果您的数字总是积极的,那么您可以做到

int result = 0;
for (int i = 0; i < tmp.length(); i++)
   result = result * 10 + tmp.charAt(i) - '0';

char是一个整数类型,它将我们的字母映射到计算机可以理解的数字(参见ascii图表 )。 字符串只是一个字符数组。 由于数字在ascii表示中是连续的,因此'1' - '0' = 49 - 48 = 1'2' - '0' = 50 - 48 = 2等。

尝试这个:

int number = Integer.parseInt("12345") 
// or 
Integer number = Integer.valueOf("12345") 

atoi对开发者来说可能有些神秘。 Java更喜欢更易读的名字

如果使用Integer.parseInt,则必须捕获异常,因为Integer.parseInt(“82.23”)或Integer.parseInt(“ABC”)将启动异常。

如果你想允许这样的事情

     atoi ("82.23") // => 82
     atoi ("AB123") // => 0

这是有道理的,然后你可以使用

     public static int atoi (String sInt)
     {
        return (int) (atof (sInt));
     }

     public static long atol (String sLong)
     {
        return (long) (atof (sLong));
     }

     public static double atof (String sDob)
     {
        double reto = 0.;

        try {
           reto = Double.parseDouble(sDob);
        }
        catch (Exception e) {}

        return reto;
     }

如果用Java编程,请使用这个,

int atoi(String str)
{
    try{
        return Integer.parseInt(str);
    }catch(NumberFormatException ex){
        return -1;   
    }
}

我回应汤姆说的话。

如果您对上述实现感到困惑,那么您可以参考以下更简单的实现。

private static int getDecValue(char hex) {
    int dec = 0;
    switch (hex) {
    case '0':
        dec = 0;
        break;
    case '1':
        dec = 1;
        break;
    case '2':
        dec = 2;
        break;
    case '3':
        dec = 3;
        break;
    case '4':
        dec = 4;
        break;
    case '5':
        dec = 5;
        break;
    case '6':
        dec = 6;
        break;
    case '7':
        dec = 7;
        break;
    case '8':
        dec = 8;
        break;
    case '9':
        dec = 9;
        break;
    default:
        // do nothing
    }
    return dec;
}

public static int atoi(String ascii) throws Exception {
    int integer = 0;
    for (int index = 0; index < ascii.length(); index++) {
        if (ascii.charAt(index) >= '0' && ascii.charAt(index) <= '9') {
            integer = (integer * 10) + getDecValue(ascii.charAt(index));
        } else {
            throw new Exception("Is not an Integer : " + ascii.charAt(index));
        }
    }
    return integer;
}

Java有一个内置函数,可以做到这一点......

String s =  "12345";
Integer result = Integer.parseInt(s);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM