I have 2 Strings.
String s1 = "x^5 + 22.6x^4 - x^3 - 41.3x^1 + 4.2";
String s2 = "-x^3 - 3x^2 + 2x + 22";
I want to split the strings. I should find coefficients and exponents.
I used replace method like this: s1.replaceAll("//s+","");
So I remove all whitespace.
When I use split method.
String array[] = s2.split("//+");
My outputs are :
-x^3-3x^2
+2x
+22
But it is not answer. Using one split method, I will divide all the parts.
But I want to split the strings when special code "+" and "-" together. But I didn't again. Without removing whitespaces, can I split my Strings?
Splitting that string isn't that complicated. But you need some knowledge about regular expressions.
I'll give you first a code snippet:
Note that this only works with syntactically correct polynomials.
There are some parsing pitfalls there. For example, you have to take care of empty strings, which represent the value "1" some times.
The main problem - however - is to get the regular expressions right.
The first one is the expression
(?=\\+|\\-)
. This uses an alternation group because you want to match either on "+" or on "-". Additionally, you want to keep the operator sign while splitting as it also is the sign for the coefficient. For this you have to use a positive lookahead (the "?=" part).Read more on regular expressions on http://www.regular-expressions.info/.
The second one is the splitting around "x" but with a fixed limit of 2. That allows the split function to also split the term "-41.3x" into the array
{"-41.3", ""}
. Without the limit, it would only be a 1-lengthed array, and that would be ambiguous with no "x" at all.And of course I initially removed all whitespaces as this simply makes parsing a lot easier.
The two output statements above produce the following results: