java - How to split a String into integers?


Keywords:java 


Question: 

I'd like to split a String, and store each digit of the String into an integer.

Here's my test code:

public class test {
    public static void main(String[] args){
        int firstGuessDigit, secondGuessDigit, thirdGuessDigit, fourthGuessDigit;
        String guess = "1234";
        String[] parts = guess.split("\");
        firstGuessDigit = Integer.parseInt(parts[0]);
        secondGuessDigit = Integer.parseInt(parts[1]);
        thirdGuessDigit = Integer.parseInt(parts[2]);
        fourthGuessDigit = Integer.parseInt(parts[3]);
    }

}

When I run the program, I get an error: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at test.main(test.java:11)


4 Answers: 

You can use String#toCharArray instead:

char[] parts = guess.toCharArray();
firstGuessDigit = Integer.parseInt(Character.toString(parts[0]));
secondGuessDigit = Integer.parseInt(Character.toString(parts[1]));
thirdGuessDigit = Integer.parseInt(Character.toString(parts[2]));
fourthGuessDigit = Integer.parseInt(Character.toString(parts[3]));
 

You can get the characters of the string using the chars() stream and map them to their numeric values with Character.getNumericValue:

"1234".chars().map(Character::getNumericValue).toArray()

If you prefer to get them as a list instead of an array, you can use:

"1234".chars().map(Character::getNumericValue).boxed().collect(Collectors.toList())
 

The error you getting is because you are trying to do parts[1] when it doesn't have it.

Code you are looking for is:

String guess = "1234";
int[] guessInteger = new int[guess.length()];
int i=0;
for(Character ch : guess.toCharArray()){
    if(Character.isDigit(ch)){
        guessInteger[i++] = Character.getNumericValue(ch);
    }
}
 

This should do it.

public class Test {

    public static void main(String[] args) {

        int firstGuessDigit, secondGuessDigit, thirdGuessDigit, fourthGuessDigit;
        String guess = "1234";

        String[] parts = new String[4];
        for(int i = 0; i < 4; i++) {
            parts[i] = ""+guess.charAt(i);
        }

        firstGuessDigit = Integer.parseInt(parts[0]);
        secondGuessDigit = Integer.parseInt(parts[1]);
        thirdGuessDigit = Integer.parseInt(parts[2]);
        fourthGuessDigit = Integer.parseInt(parts[3]);

    } 

}