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?
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?
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.
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.)
String.split
accepts regular expressions, so try split("[-+]")
.