Java – How to split a given String using either + or –

javastring

I want to split a polynomial like:

2x^7+x^2+3x-9

Into each one of its terms (2x^7, x^2, 3x, 9)

I've thought about using String.split(), but how can I make it take more than one paramether?

Best Solution

split takes a regular expression, so you can do:

String[] terms = myString.split("[-+]");

and it will split when it encounters either + or -.

Edit: Note that as Michael Borgwardt said, when you split like this you cannot tell which operator (+ or -) was the delimiter. If that's important for your use, you should use a StringTokenizer as he suggested. (If you're trying to write a math expression parser, neither of these will be of much help, though.)