Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually converting a string to an integer in Java

I'm having string consisting of a sequence of digits (e.g. "1234"). How to return the String as an int without using Java's library functions like Integer.parseInt?

public class StringToInteger {
  public static void main(String [] args){
    int i = myStringToInteger("123");
    System.out.println("String decoded to number " + i);
  }

  public int myStringToInteger(String str){
      /* ... */
  }
}
like image 709
Manu Avatar asked Jan 17 '12 11:01

Manu


People also ask

Which method converts string to integer?

We can convert String to an int in java using Integer. parseInt() method. To convert String into Integer, we can use Integer. valueOf() method which returns instance of Integer class.

Can you convert a string into a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.


1 Answers

And what is wrong with this?

int i = Integer.parseInt(str);

EDIT :

If you really need to do the conversion by hand, try this:

public static int myStringToInteger(String str) {
    int answer = 0, factor = 1;
    for (int i = str.length()-1; i >= 0; i--) {
        answer += (str.charAt(i) - '0') * factor;
        factor *= 10;
    }
    return answer;
}

The above will work fine for positive integers, if the number is negative you'll have to do a little checking first, but I'll leave that as an exercise for the reader.

like image 138
Óscar López Avatar answered Sep 20 '22 00:09

Óscar López