Ajay Victor Ajay Victor - 3 months ago 10x
Java Question

Split Numbers within parenthesis in Java

I would like to split this input:

12132002(177) 012(207.5) 014(184)
into two arrays, like this:

num[500] = 12132002,012,014, etc.

mark[500] = 177,207.5,184, etc.

The Fact is that I'm accepting values from user like this, where i don't know the total number which he/she will input.

How can I code in Java that kind of splitting? Is it like this?

int number[500];
for(int i=0;i<500;i++) {


To code "that kind of splitting", you will have to:

  1. Declare your variables: String[] number, String[] mark, String num, and String[] numSplit.
  2. Split num by " " (spaces). Assign this to numSplit.
  3. Loop through numSplit from 0 to numSplit.length with i.
  4. Set number[i] to numSplit[i] from the beginning to the first occurrence of a "(".
  5. Set mark[i] to numSplit[i] from one character after the first occurrence of "(" to one character before the end.
  6. Output number and mark

The full code:

String[] number = new String[500]; //1
String[] mark = new String[500];
String num = "12132002(177) 012(207.5) 014(184)";
String[] numSplit = num.split(" "); //2

for(int i = 0; i < numSplit.length; i++) { //3
    number[i] = numSplit[i].substring(0, numSplit[i].indexOf("(")); //4
    mark[i] = numSplit[i].substring(numSplit[i].indexOf("(") + 1, numSplit[i].length() - 1); //5

for(int i = 0; i < number.length; i++) System.out.println(number[i]); //6
for(int i = 0; i < mark.length; i++)  System.out.println(mark[i]);

Which outputs:

null (x497)
null (x497)

Notice that number, mark, and numSplit are String arrays because the leading zeros would be cut off in not otherwise. If you don't mind the leading zeros being cut off then you can change num to an int array and mark to a double array (Because of the decimal in 207.5).