简体   繁体   中英

How do I convert a string of numbers to an integer array?

I have a string like, "12345" and want to convert it to the integer array, {1,2,3,4,5} .

I want one method to convert a character to an integer, '1' -> 1 . And another method to create the array.

This is what I have so far:

public static int charToInt(char character) {
    int newInt;

    newInt = (int) character;

    return newInt;
}

public static int[] convertStringToIntArray(String keyString) {
    int keyLength = keyString.length();
    int element;

    int[] intArray = new int[keyLength];

    for (element = 0; element < keyLength; element++) {
        intArray[element] = charToInt(keyString.charAt(element));
    }

    // return
    return intArray;
}

I think the problem is in the charToInt method. I think it is converting the char to its ascii value. But I am not sure if the other method is right either.

Any help would be greatly appreciated.

Since Java 1.5 Character has an interesting method getNumericValue which allows to convert char digits to int values.

So with the help of Stream API, the entire method convertStringToIntArray may be rewritten as:

public static int[] convertStringToIntArray(String keyString) {
    Objects.requireNonNull(keyString);
    return keyString.chars().map(Character::getNumericValue).toArray();
}

This might help -

int keyLength = keyString.length();
int num = Integer.parseInt(keyString);
int[] intArray = new int[ keyLength ];

for(int i=keyLength-1; i>=0; i--){
    intArray[i] = num % 10;
    num = num / 10;
}

You are right. The problem here is in charToInt .
(int) character is just the ascii codepoint (or rather UTF-16 codepoint).

Because the digits '0' to '9' have increasing codepoints you can convert any digit into a number by subtracting '0' .

public static int charToInt(char digit)
{
   return digit - '0';
}

Since Java 9 you can use String#codePoints method.

Try it online!

public static int[] convertStringToIntArray(String keyString) {
    return keyString.codePoints().map(Character::getNumericValue).toArray();
}
public static void main(String[] args) {
    String str = "12345";
    int[] arr = convertStringToIntArray(str);

    // output
    System.out.println(Arrays.toString(arr));
    // [1, 2, 3, 4, 5]
}

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