Danish Ali
Danish Ali

Reputation: 147

Split String into Array based on multiple delimiters in Java

I am trying to split a string into two different arrays based on multiple values

For example user inputs in the console window

   2+4/8*9

I want only the numbers to be in an array

Arr[0] = 2;
Arr[1] = 4;
Arr[2] = 8;
Arr[3] = 9;

And then

Operator[0] = +;
Operator[1] = /;
Operator[2] = *;

I am familiar with split method that uses only one delimiter but how will I be able to split the string based on various number of delimiters?

Following is the latest code I have tried by looking at various articles on the internet but getting error

Scanner in = new Scanner(System.in);
System.out.println("Enter input");
s = in.toString();

String [] operators = s.split("+|-|*|/"); //Also tried s.split("\\+\\-\\*\\/")

for(int i = 0; i<operators.length; i++) {
    System.out.println(operators[i]);
}

Upvotes: 0

Views: 3712

Answers (4)

arg0100
arg0100

Reputation: 21

Using Regex we can split the expression and store the operand in String[]

String[] t = st.split("-|\\#|\\(|\\)|\\{|\\}|\\<|\\>|\\s+|\\(\\\"|\\;");

The regex expression split String based on "-, #, (, ), {, }, <, >, space, ;, #" for character like "(double quote) and (backlash) then iterate the elements of String and remove the char.

Upvotes: 1

John S.
John S.

Reputation: 646

Try this.

String str = "2+2-4*5/6";
str = str.replaceAll(" ", "");
String[] Arr = str.replaceAll("[\\+\\-\\*\\/]", " ").split(" ");
String[] Operator = str.replaceAll("[0-9]", " ").split(" ");

Hope that helps!

Upvotes: 1

devops
devops

Reputation: 9177

Use non-digit Regex to split your string:

String input     = "14*6+22";
String[] spl     = input.split("\\D");
char[] operation = input.replaceAll("\\w", "").toCharArray();

System.out.println(Arrays.toString(spl));
System.out.println(Arrays.toString(operation));

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

The string argument in split is a regular expression.

*, +, -, and / have special meanings in a regular expression. (The asterisk means "match any").

You need to escape them if you want to match them as exact symbols.

To do that use \\* etc. \* means a literal asterisk in a regular expression: in Java you need to escape the backslash; you do that by writing \\.

So you ought to use something like

\\+|\\-|\\*|\\/

Upvotes: 1

Related Questions