Java Program to Convert a String to an Integer Array

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.

  1.  
  2. //Java Program to Convert a String to an Integer Array
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7.  
  8. public class StringToIntegerArray {
  9.     // Function to convert String into an Integer array
  10.     static int[] toIntegerArray(String str){
  11.         int 
  12.         String[] splitArray = str.split(" ");
  13.         int[] array = new int[splitArray.length];
  14.         for(i=0;i<splitArray.length;i++)
  15.         {
  16.                 try {
  17.                     array[i] = Integer.parseInt(splitArray[i]);
  18.                 } catch (NumberFormatException e) {
  19.                     array[i]=-1;
  20.                 }
  21.         }
  22.         return array;
  23.     }
  24.     // main function to read the string
  25.     public static void main(String[] args) {
  26.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  27.         String str;
  28.         System.out.println("Enter the string");
  29.         try {
  30.             str = br.readLine();
  31.         }
  32.         catch (IOException e){
  33.             System.out.println("An I/O error occurred");
  34.             return;
  35.         }
  36.         int i;
  37.         int[] array=toIntegerArray(str);
  38.         System.out.println("The contents of the array are");
  39.         for(i=0;i<array.length;i++){
  40.             System.out.print(array[i]+" ");
  41.         }
  42.     }
  43. }
Program Explanation

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.

advertisement
advertisement

Time Complexity: O(n) where n is the length of the string.

Runtime Test Cases
 
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.

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.