简体   繁体   中英

atoi in java using charAt

I know that one solution to do this is the following:

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

What I don't understand is why is:

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

How can this convert into a digit?

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

In the ascii table , characters from '0' to '9' are contiguous. So, if you know that tmp.charAt(i) will return a character between 0 and 9 , then subracting 0 will return the offset from zero, that is, the digit that that character represents.

Using Math.pow is very expensive, you would be better off using Integer.parseInt.

You don't have to use Math.pow. If your numbers are always positive you can do

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

char is an integer type that maps our letters to numbers a computer can understand (see an ascii chart ). A string is just an array of characters. Since the digits are contiguous in ascii representation, '1' - '0' = 49 - 48 = 1 , '2' - '0' = 50 - 48 = 2 , etc.

Try this:

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

atoi could be a bit mistery for developers. Java prefers more readable names

If using Integer.parseInt you have to catch exceptions, since Integer.parseInt("82.23") or Integer.parseInt("ABC") will launch exceptions.

If you want to allow things like

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

which makes sense then you can use

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

If programming in Java, please use this,

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

I echo what Tom said.

If you are confused with the above implementation then you can refer the below simpler implementation.

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 has a built in function that does this...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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