Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

java - How to Split a mathematical expression on operators as delimiters, while keeping them in the result?

I need to split an expression like

a+b-c*d/e 

and get a, b, c, d, e seperately(as array of strings) as well as =,-,*,d,/(also an array of operators) separately. I have tried like:

String myString;

String myString={"a+b-c*d/e");

String[] result=new String();

String[] separator=new String[]{"+","-","/","*"};

result=myString.split(separator);

But, it shows an error. How to solve it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

1st problem: -

Multiple declaration of String myString;

2nd problem: -

String initialized incorrectly. Double quotes missing at the ends. Remove bracket and brace from the ends.

String myString = "a+b-c*d/e";

3rd problem: -

String array initialized with an String object, rather than an array object.

String[] result=new String();  // Should be `new String[size]`

In fact, you don't need to initialize your array before hand.

4th problem: -

String.split takes a Regular Expression as argument, you have passed an array. Will not work.

Use: -

String[] result = myString.split("[-+*/]");

to split on all the operators.


And regarding your this statement: -

as well as =, -, *, d, / (also an array of operators) separately.

I don't understand what you want here. Your sample string does not contains =. And d is not an operator. Please see if you want to edit it.

UPDATE : -

If you mean to keep the operators as well in your array, you can use this regex: -

String myString= "a+b-c*d/e";
String[] result = myString.split("(?<=[-+*/])|(?=[-+*/])");
System.out.println(Arrays.toString(result));

/*** Just to see, what the two parts in the above regex print separately ***/
System.out.println(Arrays.toString(myString.split("(?<=[-+*/])")));
System.out.println(Arrays.toString(myString.split("(?=[-+*/])")));

OUTPUT : -

[a, +, b, -, c, *, d, /, e]
[a+, b-, c*, d/, e]
[a, +b, -c, *d, /e]

(?<=...) means look-behind assertion, and (?=...) means look-ahead assertion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...