Grails Cookbook - A collection of tutorials and examples

Split String Into Array Of Integers in Java

Remember that the String.split() method splits a String into an array of substrings given a specific delimter. Each susbtring represents a number, which can be converted into an array of integer.

Java Split String Into Array Of Integers Example

If you want to convert a String Array into an Integer Array, take note that there's no built-in utility class for this. Some programmers are aware that it's possible using other utilities since it is not found in the standard package. That maybe true, but let's try the process through coding manually. In order to split string into an array of integers, it's necessary to invoke the parseInt method of the integer class on each substring.

Check out the program below:

public class SplitStringIntoArrayOfIntegerExample {
    public static void main(String[] args) {
       String theStr = "97,21,33";
       String[] strArr = theStr.split(",");
       int[] intArr = new int[strArr.length];
       for (int i = 0; i < strArr.length; i++) {
          String num = strArr[i];
          intArr[i] = Integer.parseInt(num);
       }
       for (int n : intArr) {
          System.out.println(n);
       }
    }
 }
There should be a single loop to go through each element to perform the conversion One single loop through each element is all it takes to perform the conversion we need. Check out the expected result below:
97
212
33
Unfortunately, there seems no one function call in current Java api to do this, so we would need to do our own logic as shown above. As of now, this is the easiest way to do it. We could also refactor it into a function:
public class SplitStringIntoArrayOfIntegerExample {
    public static int[] splitStrToIntArr(String theStr) {
       String[] strArr = theStr.split(",");
       int[] intArr = new int[strArr.length];
       for (int i = 0; i < strArr.length; i++) {
          String num = strArr[i];
          intArr[i] = Integer.parseInt(num);
       }
       return intArr;
    }
    public static void main(String[] args) {
       String theStr = "97,21,33";
       int[] intArr = splitStrToIntArr(theStr)
       for (int n : intArr) {
          System.out.println(n);
       }
    }
 }
And this should behave similar to the example above.