Convert Java String to Int Array

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.

Output

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.

Output

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.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *