Java Program to Convert String to Integer Array
Strings – Strings in Java are objects that are supported internally by a char array. Since arrays are immutable, and strings are also a type of exceptional array that holds characters, therefore, strings are immutable as well.
Integer Array – An array is a combination of the same type of variables. Likewise, a collection of integers (int) referred to by a common name is an Integer Array.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Problem Statement – Given a string, the task is to convert that string into an integer array.
Let us first go through few examples to make it more clear.
Input : String : "1 23 456 7890" Output : Integer array : [1 23 456 7890]
Input : String : "[1,2,356,678,3378]" Output : Integer array : [1, 2, 356, 678, 3378]
There are numerous approaches to do the same; a few of them are listed below.
- Using string.replaceAll() method
- Using string.split() method
Method 1 – Using string.replaceAll() method
The string.replaceAll() method takes two arguments, a regex, and the replacement values. This method will replace the given regex with the given replacement value, and after that, the split() method is used to split the string.
String : [1,2,356,678,3378] Integer array : [1, 2, 356, 678, 3378]
Method 2 – Using string.split() method
The string.split() method is used to split the string into various sub-strings. Then, those sub-strings are converted to an integer using the Integer.parseInt() method and store that value integer value to the Integer array.
String : 1 23 456 7890 Integer array : [1 23 456 7890 ]