Search code examples
javaarraysstringstringtokenizerparseint

Converting string into array of ints ex String st = "1 2 3 4 5" into ar=[1,2,3,4,5]


I am reading in a string, as an entire line of numbers, separated by spaces, ie ie 1 2 3 4 5. I want to convert them into an array of integers, so that I can manipulate them. But this code doesn't work. It says incompatible types.

String str = br.readLine();
int[] array = new int[4];
StringTokenizer tok = new StringTokenizer(str," ", true);
boolean expectDelim = false;
int i = 0;

while (tok.hasMoreTokens()) {
    String token = tok.nextToken();
    ar[i] = Integer.parseInt(token);
    i++;
}

Solution

  • If you have a String s = "1 2 3 4 5" then you can split it into separate bits like this:

    String[] bits = s.split(" ");
    

    Now you have to put them into an int[] by converting each one:

    int[] nums = new int[bits.length];
    int i=0;
    for (String s: bits)
        nums[i++] = Integer.parseInt(s);
    

    This will loop through each of the small strings in the split array, convert it to an integer, and put it into the new array.