Convert String to array of integer in java

后端 未结 5 1915
悲&欢浪女
悲&欢浪女 2021-01-29 15:01

Outline how a Java program could convert a string such as “1,2,3,4,5” into an array ({1, 2, 3, 4,5})

5条回答
  •  孤城傲影
    2021-01-29 15:29

    Use StringTokenizer which will split string by comma and then put those values/tokens in array of integers.

    public static int[] getIntegers(String numbers) {
        StringTokenizer st = new StringTokenizer(numbers, ",");
        int[] intArr = new int[st.countTokens()];
        int i = 0;
        while (st.hasMoreElements()) {
            intArr[i] = Integer.parseInt((String) st.nextElement());
            i++;
        }
        return intArr;
    }
    

提交回复
热议问题