0

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]);
}
2
  • 1
    Possible duplicate of Java String.split() Regex Commented Jan 26, 2016 at 15:35
  • Use Spring.split() method and pass the Regex as an argument to the method. Commented Jan 26, 2016 at 15:42

4 Answers 4

1

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Tried this now getting this error java.util.Scanner[delimiters=\p{javaWhitespace} ][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q \E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]
1

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!

Comments

1

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.

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.