This is the Java Program to Convert a String to an Integer Array.
Problem Description
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].
Problem Solution
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.
Program/Source Code
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