8

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?

xonegirlz
  • 8,889
  • 19
  • 69
  • 127
  • Are you simply trying to convert a string to an int? – PTBG Nov 07 '11 at 16:07
  • yes I am.. and I'd have to write my own function, kind of an atoi in C – xonegirlz Nov 07 '11 at 16:07
  • Is this homework? If not, just use `Integer.valueOf("12345")`. If it is, please tag it as such. – Ted Hopp Nov 07 '11 at 16:08
  • @xonegirlz - did you try my solution? If it worked then please accept the answer and vote up! – JRG Jul 26 '17 at 05:53
  • Possible duplicate of [How to convert a String to an int in Java?](https://stackoverflow.com/questions/5585779/how-to-convert-a-string-to-an-int-in-java) – Clijsters Aug 15 '17 at 14:10
  • If @PTBG is right and you want to convert Strings to Ints, this question is a duplicate: https://stackoverflow.com/questions/5585779/how-to-convert-a-string-to-an-int-in-java – Clijsters Aug 15 '17 at 14:11

8 Answers8

13

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.

Tom
  • 43,810
  • 29
  • 138
  • 169
11

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';
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
7

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.

Kevin
  • 53,822
  • 15
  • 101
  • 132
3

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

lukastymo
  • 26,145
  • 14
  • 53
  • 66
1

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;
     }
elxala
  • 291
  • 3
  • 5
1

If programming in Java, please use this,

int atoi(String str)
{
    try{
        return Integer.parseInt(str);
    }catch(NumberFormatException ex){
        return -1;   
    }
}
Bharathkumar V
  • 327
  • 5
  • 13
  • 1
    While this is correct and - imho - answers the question, it qould benefit from more contextual information like, what `parseInt()` is, what it does, and where one can find it's documentation. – Clijsters Aug 15 '17 at 14:09
  • Sure. Static method `parseInt()` verifies if characters in string are decimals except for first one, which could be minus sign. [link]https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String) – Bharathkumar V Aug 15 '17 at 14:21
  • Please use the edit functionality on your question. See [How do I write a good answer](https://stackoverflow.com/help/how-to-answer) in the help center. – Clijsters Aug 15 '17 at 15:33
0

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;
}
JRG
  • 4,037
  • 3
  • 23
  • 34
0

Java has a built in function that does this...

String s =  "12345";
Integer result = Integer.parseInt(s);
PTBG
  • 585
  • 2
  • 20
  • 46