1

我有 2 个字符串。

String s1 = "x^5 + 22.6x^4 - x^3 - 41.3x^1 + 4.2";
String s2 = "-x^3  -  3x^2 + 2x + 22";

我想拆分字符串。我应该找到系数和指数。我使用了这样的替换方法:s1.replaceAll("//s+","");所以我删除了所有空格。当我使用拆分方法时。

String array[] = s2.split("//+");

我的输出是:

-x^3-3x^2
+2x
+22

但这不是答案。使用一种拆分方法,我将拆分所有部分。

但是我想在特殊代码“+”和“-”在一起时拆分字符串。但我又没有。在不删除空格的情况下,我可以拆分我的字符串吗?

4

2 回答 2

0

一种方法是遍历不包含空格的 polinome 的所有子字符串(基本上是所有变量和运算符本身。然后您可以决定在当前迭代中是否看到运算符或其他内容并分别处理它们。如果你不看一个运算符,你可以用字符 ^ 分割你当前的匹配,第 0 个找到是你的系数,第 1 个是你的指数。

    Pattern pattern = Pattern.compile("([^ ]+)");
    Matcher matcher = pattern.matcher("x^5 + 22.6x^4 - x^3 - 41.3x^1 + 4.2");

    while (matcher.find()) {
        String match = matcher.group(1);
        if (Arrays.asList("+", "-").contains(match)) {
            // something you do with operators
        }

        if (match.matches(".*\\^.*")) {
            // your match is 'x^y' format
            String[] split = match.split("\\^");
            String coefficient = split[0]; // your coefficient
            String exponent = split[1]; // your exponent

            System.out.println(coefficient + " ^ "+exponent); // see your result

        } else {
            // something you do when the current variable doesn't have an exponent
        }
    }
于 2014-11-12T09:26:13.127 回答
0

拆分该字符串并不复杂。但是你需要一些关于正则表达式的知识。

我先给你一个代码片段:

String poly = "x^5 + 22.6x^4 - x^3 - 41.3x + 4.2";
String[] terms = poly.replace(" ", "").split("(?=\\+|\\-)");
System.out.println(Arrays.toString(terms));

Map<Integer, Double> analyzed = new HashMap<>();
for (String term : terms)
{
    String[] splitAroundX = term.split("x", 2);
    int exponent = 0;
    if (splitAroundX.length > 1)
    {
        String sExp = splitAroundX[1].replace("^", "");
        exponent = sExp.isEmpty() ? 1 : Integer.parseInt(sExp);
    }
    String sCoeff = splitAroundX[0];
    double coefficient =
        sCoeff.isEmpty() ? 1.0 : ("-".equals(sCoeff) ? -1.0 : Double.parseDouble(sCoeff));
    analyzed.put(Integer.valueOf(exponent), Double.valueOf(coefficient));
}
System.out.println(analyzed);

请注意,这只适用于语法正确的多项式。

那里有一些解析陷阱。例如,您必须处理空字符串,这些字符串有时表示值“1”。

然而,主要问题是正确使用正则表达式。

第一个是表达式(?=\\+|\\-)。这使用了一个交替组,因为您想在“+”或“-”上进行匹配。此外,您希望在拆分时保留运算符符号,因为它也是系数的符号。为此,您必须使用积极的前瞻(“?=”部分)。

在http://www.regular-expressions.info/上阅读更多关于正则表达式的信息。

第二个是围绕“x”拆分,但固定限制为 2。这允许拆分函数也将术语“-41.3x”拆分为数组{"-41.3", ""}。如果没有这个限制,它只会是一个长度为 1 的数组,而且根本没有“x”,这将是模棱两可的。

当然,我最初删除了所有空格,因为这只会使解析变得容易得多。

上面的两个输出语句产生以下结果:

[x^5, +22.6x^4, -x^3, -41.3x, +4.2]

{0=4.2, 1=-41.3, 3=-1.0, 4=22.6, 5=1.0}

于 2014-11-12T09:43:47.150 回答