how to convert string to number without using library function

Without using a library function, subtract the character '0' from each numeric character to give you its int value, then build up the number by multiplying the current sum by 10 before adding the next digit's ìnt value.

Java 7

public static int getNumber(String number) {
    int result = 0;
    for (int i = 0; i < number.length(); i++) {
        result = result * 10 + number.charAt(i) - '0';
    }
    return result;
}

Java 8

public static int getNumber(String number) {
    return number.chars().reduce(0, (a, b) -> 10 * a + b - '0');
}

This works primarily because the characters 0-9 have consecutive ascii values, so subtracting '0' from any of them gives you the offset from the character '0', which is of course the numeric equivalent of the character.


Disclaimer: This code does not handle negative numbers, arithmetic overflow or bad input.

You may want to enhance the code to cater for these. Implementing such functionality will be instructive, especially given this is obviously homework.


Here's some test code:

public static void main(String[] args) {
    System.out.println(getNumber("12345"));
}

Output:

12345

Tags:

Java