Convert Java String to int array example shows how to convert Java String to integer array. It also shows how to do it using the replaceAll and parseInt methods.
How to convert Java String to an int array?
This example shows how to convert a string like “[1,2,3,4,5]” to an int array. In order to convert this string to an integer array, we first need to remove the square brackets from the string using the replace method.
Once we get rid of the square brackets, we need to make sure that the string does not contain anything except for the numbers and commas. This includes spaces as well. We can do that by replacing all the spaces from the string with the empty string.
Finally, we need to split the string using the split method that returns an array. Once we get the array, we need to iterate the array and convert the string to int and add it to the int array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.javacodeexamples.stringexamples; public class StringToIntArray { public static void main(String[] args) { String strNumbers = "[1,2,3,4, 5]"; //remove square brackets strNumbers = strNumbers.replace("[", "").replace("]", ""); //remove all spaces strNumbers = strNumbers.replace(" ", ""); //split the string by comma using the split method String[] strParts = strNumbers.split(","); //create new int array having same size int[] intArray = new int[ strParts.length ]; //iterate the string array for(int i = 0 ; i < strParts.length ; i++) { //parse the string to int and add to the array intArray[i] = Integer.parseInt(strParts[i]); } System.out.println("integer array contains: "); for(int i : intArray) { System.out.println(i); } } } |
Output
1 2 3 4 5 6 |
integer array contains: 1 2 3 4 5 |
If your string contains curly brackets instead of square brackets, you can adjust the replace
method accordingly.
We can also use the replaceAll
method instead of the replace
method to make the code short. Since the replaceAll
method accepts the regex pattern, we can remove everything except numbers and commas in a one go using the “[^0-9,]” pattern.
Along with the replaceAll
method, this pattern removes everything that is not a digit between 0 to 9 and a comma. Here is the updated example code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
String strNumbers = "[1,2,3,4, 5]"; String[] strParts = strNumbers.replaceAll("[^0-9,]", "").split(","); int[] intArray = new int[ strParts.length ]; for(int i = 0 ; i < strParts.length ; i++) { intArray[i] = Integer.parseInt(strParts[i]); } System.out.println("integer array contains: "); for(int i : intArray) { System.out.println(i); } |
Output
1 2 3 4 5 6 |
integer array contains: 1 2 3 4 5 |
If you want to learn more about the string in Java, please visit the Java String tutorial.
Please let me know your views in the comments section below.