Convert String to array of integer in java

后端 未结 5 1914
悲&欢浪女
悲&欢浪女 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:23
    String [] str = "1,2,3,4,5".split(",");
    int arrayInt[] = new int[str.length];
    for (int i = 0; i < str.length; i++) 
        arrayInt[i]=Integer.valueOf(str[i]);
    
    0 讨论(0)
  • 2021-01-29 15:25

    From zvzdhk:

    String[] array = "1,2,3,4,5".split(",");
    

    Then, parse your integers:

    int[] ints = new int[array.length];
    for(int i=0; i<array.length; i++)
    {
        try {
            ints[i] = Integer.parseInt(array[i]);           
        } catch (NumberFormatException nfe) {
            //Not an integer 
        }
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • Try this:

    String[] array = "1,2,3,4,5".split(",");
    int[] result = new result[array.length];
    for (int i = 0; i < array.length; i++) {
        try {
             result[i] = Integer.parseInt(array[i]);
        } catch (NumberFormatException nfe) {};
    }
    
    0 讨论(0)
  • 2021-01-29 15:33

    With Guava you can do this in one line:

    int[] array = Ints.toArray(Lists.newArrayList(Ints.stringConverter().convertAll(Splitter.on(",").split("1,2,3,4,5"))));
    

    or so (if you don't require an array):

    Iterable<Integer> ints = Ints.stringConverter().convertAll(Splitter.on(",").split("1,2,3,4,5"));
    
    0 讨论(0)
提交回复
热议问题