This is the Java Program to Convert a String to an Integer Array.
Given a string consisting of various numbers separated by spaces, convert it into an array of Integers, such that every number occupies a position in the array, and for every invalid number, there is a -1 in the array.
Example:
For the String str = “19 46 8999 abc 133”;
The array will be [19, 46, 8999, -1, 133].
The idea is to split the string into various substrings whenever space is encountered while traversing through the string, and then convert those substrings into the integers they represent.
Here is the source code of the Java Program to Convert a String to an Integer Array. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Convert a String to an Integer Array
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StringToIntegerArray {
// Function to convert String into an Integer array
static int[] toIntegerArray(String str){
int
String[] splitArray = str.split(" ");
int[] array = new int[splitArray.length];
for(i=0;i<splitArray.length;i++)
{
try {
array[i] = Integer.parseInt(splitArray[i]);
} catch (NumberFormatException e) {
array[i]=-1;
}
}
return array;
}
// main function to read the string
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter the string");
try {
str = br.readLine();
}
catch (IOException e){
System.out.println("An I/O error occurred");
return;
}
int i;
int[] array=toIntegerArray(str);
System.out.println("The contents of the array are");
for(i=0;i<array.length;i++){
System.out.print(array[i]+" ");
}
}
}
1. In function toIntegerArray(), the string is split into various tokens using s.split(” “) statement.
2. The loop for(i=0;i<splitArray.length;i++) is used to iterate through the array of tokens.
3. Using a try block, the current token is converted into integer through Integer.parseInt(splitArray[i]).
4. If the conversions fails, the catch block catches the failure and sets the value of array[i] to -1.
Time Complexity: O(n) where n is the length of the string.
Case 1 (Simple Test Case - all integers): Enter the string 12 23 34 45 56 67 78 89 The contents of the array are 12 23 34 45 56 67 78 89 Case 2 (Simple Test Case - all strings): Enter the string abc pqr xyz The contents of the array are -1 -1 -1 Case 3 (Simple Test Case - mixed values): Enter the string 99999 z 1244765 989 The contents of the array are 99999 -1 1244765 989
Sanfoundry Global Education & Learning Series – Java Programs.
- Apply for Computer Science Internship
- Practice Information Technology MCQs
- Practice BCA MCQs
- Apply for Java Internship
- Check Java Books