java - 多项式字符串未拆分

标签 java string polynomials

我有 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+",""); 所以我删除了所有空格。 当我使用 split 方法时。

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

我的输出是:

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

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

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

最佳答案

一种方法是迭代 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
        }
    }

关于java - 多项式字符串未拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26883037/

相关文章:

c++ - 字符串有问题。调试声称 "bad pointer"

python 多变量多项式包

java - 多项式拉格朗日函数以获得正确的系数

java - 创建 jar 文件时出现问题

java - 描述实例的最简单方法

java - 如何在Java中提取包含多个括号的子字符串?

algorithm - 分母为导数的 Durand-Kerner

java - Jsoup http 日志记录

java - 为什么这会导致堆栈溢出错误?有向图

javascript - 使用 NodeJS 查找 URL 中的子字符串