Skip to content
Advertisement

How do I split the plus minus number string in java? [closed]

Input :

String arrr[] = new String[4];

arrr[0] = +2501 +2502 +2503 +2504

arrr[1] = -2501 -2504 +2505 +2506 +2507 +2509

arrr[2] = +2501 +2511 -2502 -2505

arrr[3] = +2513 -2507 -2503 -2511 -2509

Output :

I want separte the string as :

Positive :

arrr1[0] = +2501 +2502 +2503 +2504

arrr1[1] = +2505 +2506 +2507 +2509

arrr1[2] = +2501 +2511

arrr1[3] = +2513

Negative :

arrr2[0] = -2501 -2504

arrr2[1] = -2502 -2505

arrr2[2] = -2507 -2503 -2511 -2509

JavaScript

Advertisement

Answer

You can split the string on one or more whitespace characters (i.e. s+) and iterate the resulting array to find if an element starts with a positive symbol or a negative symbol.

Demo:

JavaScript

Output:

JavaScript

Alternatively, you can also use regex, +d+|-d+ which means one or more digits followed by a plus symbol (i.e. +d+) or (i.e. |) one or more digits followed by a negative symbol (i.e. -d+).

JavaScript

Output:

JavaScript

In case you want to use StringBuilder instead of the List:

JavaScript

Output:

JavaScript

Using String#matches:

JavaScript

Output:

JavaScript

Update (based on the updated question):

If the strings in your question are elements of a String[], you need an additional loop to iterate this String[]. Rest of the things will remain the same.

JavaScript

Output:

JavaScript
Advertisement