簡體   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