andandandand
andandandand

Reputation: 22270

How can I split a given String using either + or -?

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?

Upvotes: 3

Views: 4851

Answers (3)

Michael Myers
Michael Myers

Reputation: 191945

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

Upvotes: 9

John Kugelman
John Kugelman

Reputation: 361675

String.split accepts regular expressions, so try split("[-+]").

Upvotes: 2

Michael Borgwardt
Michael Borgwardt

Reputation: 346317

This sounds like a perfect application for the StringTokenizer class:

StringTokenizer st = new StringTokenizer("2x^7+x^2+3x-9", "+-", true);

Will return the tokens ("2x^7", "+", "x^2", "+", "3x", "-", "9") - you do need the signs to have the full information about the polynomial. If not, leave off the laster constructor parameter.

Upvotes: 6

Related Questions