Convert String to Int Array in Java

  1. Convert String to Int Array Using the replaceAll() Method
  2. Convert String to Int Array Using Java8 Stream Library
  3. Convert String to Int Array Using StringTokenizer and Functions

In the Java language, there can be several approaches to think over the problem statement.

Let us first break the problem statement into two parts.

  1. Convert a simple String to the String array.
  2. Convert a String array to an int array.

Here is the diagrammatic representation of the above two steps:

flow chart string to int in Java

Convert String to Int Array Using the replaceAll() Method

We can use the replaceAll() method of the String class that takes two arguments, regex and replacement values. This method will replace the given regex with the given replacement value. And at the end of the chain functions, the split() method is used. This method splits the String based on the character given.

We should use the Integer.parseInt() function when the values are split and collected in a String array. Since the parseInt() method throws NumberFormatException, so the statement should be in one try...catch block to catch the possibly exception.

Below is the sample program to demonstrate the conversion of strings to int array:

package stringToIntArray;

import java.util.Arrays;

public class ConvertStringToIntArray {
    public static void main(String... args) {
        
        String testString = "[1,2,356,678,3378]";
        
        String[] separatedStrings = testString.replaceAll("\\[", "")
            .replaceAll("]", "").split(",");
        
        int[] intArray = new int[separatedStrings.length];
        
        for (int i = 0; i < separatedStrings.length; i++) {
            
            try {
                intArray[i] = Integer.parseInt(separatedStrings[i]);
            } catch (Exception e) {
                System.out.println("Unable to parse string to int: " + e.getMessage());
            }
        }
        
        System.out.println(Arrays.toString(intArray));
    }
}

Output:

[1,2,356,678,3378]

If testString has value as [1,2,356,678,3378,f], it will throw an exception, and the output will look like this.

Unable to parse string to int: For input string: "f"
[1, 2, 356, 678, 3378, 0]

Convert String to Int Array Using Java8 Stream Library

In the below program, first, we have taken the Arrays.stream() function. To provide a stream to this, we have used the substring() method of the String class, which takes the first and last index parameters. Over the returned String split() function is applied, which splits the given String based on a delimiter.

Over the stream map() function is applied. This function takes any function as an argument and returns the stream. We have given the trim() function of String class which eliminated the leading and succeeding whitespaces. parseInt transforms the given String received to int. toArray() dumps converted int elements to an Array.

package stringToIntArray;

import java.util.Arrays;

public class StringToIntUsingJava8Stream {
        public static void main(String[] args) {
        
        String str = "[1, 2, 3, 4, 5]";
        
        int[] arr = Arrays.stream(str.substring(1, str.length() - 1).split(","))
                .map(String::trim).mapToInt(Integer::parseInt).toArray();
                
        System.out.println(Arrays.toString(arr));
    }
    
}

Output:

[1, 2, 3, 4, 5]

Convert String to Int Array Using StringTokenizer and Functions

Instantiate StringTokenizer object using its constructor StringTokenizer(). The constructor takes the input String and the delimiter to form a tokenized String. Simultaneously create an array of String and int with size as tokens in the tokenized String.

The countTokens() method counts the tokens, which internally skips the delimiter. hasMoreTokens() checks if there are any tokens present in tokenizer String. nextToken() retrieves the next token from the String. This method throws NoSuchElementException if no-tokens are present in the String.

Iterate to convert the String tokens to int and collect in an int array.

package stringToIntArray;

import java.util.StringTokenizer;

public class StringToIntUsingStringTokenizer {
    public static void main(String[] args) {

        String testString = "[1,2,3,4]";
        StringTokenizer stk = new StringTokenizer(testString, "[,]"); 
        String[] strings = new String[stk.countTokens()];
        int[] integerArray = new int[stk.countTokens()];
        int i = 0;
        while (stk.hasMoreTokens()) {
            strings[i] = stk.nextToken();
            integerArray[i] = Integer.parseInt(strings[i]);
            i++;
        }
        for (int j = 0; j < integerArray.length; j++)
            System.out.println("number[" + j + "]=" + integerArray[j]);
    }
}

Output:

number[0]=1
number[1]=2
number[2]=3
number[3]=4
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Java String

  • Check Whether a String Contains a Substring in Java
  • Print New Line in Java
  • Related Article - Java Array

  • Generic Array Creation in Java
  • Convert Object to String in Java