views:

141

answers:

3

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?

+6  A: 

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.

Michael Borgwardt
"StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead." - from http://java.sun.com/javase/6/docs/api/java/util/StringTokenizer.html
01
Except that the split() method does *not* offer the functionality of returning the delimiters.
Michael Borgwardt
+6  A: 

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

Michael Myers
It should be "[+\\-]".
Mehrdad Afshari
I've done it enough that you'd think double-backslashes would be second nature by now, but I guess not.
Michael Myers
If performance is of concern for you, then I would recommend you Michael's solution of using a StringTokenizer.
Gaurav Saini
You can never do it enough times :-(
Brian Agnew
Why not [-+] ? Saves you a few characters (- as the first character in a pattern class loses its special range meaning)
toolkit
+2  A: 

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

John Kugelman
I think you may need to escape the '-'
Brian Agnew
unless it is at the beginning, directly after [^ or at the end :)
mihi