如何使用+或 - 分割给定的String?

时间:2022-12-26 01:38:18

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)

进入每个术语(2x ^ 7,x ^ 2,3x,9)

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

我已经考虑过使用String.split()了,但是如何才能使用多个参数呢?

3 个解决方案

#1


split takes a regular expression, so you can do:

split采用正则表达式,因此您可以:

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 Borgwardt所说,当你像这样拆分时,你无法分辨哪个运算符(+或 - )是分隔符。如果这对您的使用很重要,您应该按照他的建议使用StringTokenizer。 (如果您正在尝试编写数学表达式解析器,但这些都不会有太大帮助。)

#2


This sounds like a perfect application for the StringTokenizer class:

这听起来像是StringTokenizer类的完美应用程序:

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.

将返回令牌(“2x ^ 7”,“+”,“x ^ 2”,“+”,“3x”,“ - ”,“9”) - 您需要这些标志才能获得有关该令牌的完整信息多项式。如果没有,请不要使用laster构造函数参数。

#3


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

String.split接受正则表达式,因此请尝试split(“[ - +]”)。

#1


split takes a regular expression, so you can do:

split采用正则表达式,因此您可以:

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 Borgwardt所说,当你像这样拆分时,你无法分辨哪个运算符(+或 - )是分隔符。如果这对您的使用很重要,您应该按照他的建议使用StringTokenizer。 (如果您正在尝试编写数学表达式解析器,但这些都不会有太大帮助。)

#2


This sounds like a perfect application for the StringTokenizer class:

这听起来像是StringTokenizer类的完美应用程序:

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.

将返回令牌(“2x ^ 7”,“+”,“x ^ 2”,“+”,“3x”,“ - ”,“9”) - 您需要这些标志才能获得有关该令牌的完整信息多项式。如果没有,请不要使用laster构造函数参数。

#3


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

String.split接受正则表达式,因此请尝试split(“[ - +]”)。