Java StringTokenizer parse comma-separated list of int

Description

Java StringTokenizer parse comma-separated list of int


//package com.demo2s;

import java.util.StringTokenizer;

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "1,2,3,4";
        System.out.println(java.util.Arrays.toString(splitInts(str)));
    }/*from   w  w w .j a v  a  2  s . com*/

    /** Parse comma-separated list of ints and return as array. */
    public static int[] splitInts(String str) throws IllegalArgumentException {
        StringTokenizer tokenizer = new StringTokenizer(str, ",");

        int n = tokenizer.countTokens();
        int[] list = new int[n];
        for (int i = 0; i < n; i++) {
            String token = tokenizer.nextToken();
            list[i] = Integer.parseInt(token);
        }
        return list;
    }

}



PreviousNext

Related