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

前端 未结 5 1052
忘了有多久
忘了有多久 2020-11-29 09:36

I need to split an expression like

a+b-c*d/e 

and get a, b, c, d, e sepe

5条回答
  •  甜味超标
    2020-11-29 10:26

    As far as I know you cannot do what you are after right out of the box. The split(String regex) does not take an entire array (unlike C#), just a string representing a valid regular expression.

    What you could do would be to define a Set which contains your operators and 2 ArrayLists. Once you have that, you iterate over your string, check if the set contains that given character (thus determining if it is an operator or not). If it is, then, you put it in one list, if not, you put it in the other.

    Finally, you can then use toArray(new String\[arraySize\]) to get back your ArrayLists as String arrays.

提交回复
热议问题