如何在Java中提取多项式系数?

以字符串-2x^2+3x^1+6为例,如何从存储在字符串中的等式中提取-26

没有给出确切的答案,但有一些提示:

  • 使用替换 meyhod:

    全部替换-+-

  • 使用拆分方法:

     // after replace effect String str = "+-2x^2+3x^1+6" String[] arr = str.split("+"); // arr will contain: {-2x^2, 3x^1, 6} 
  • 现在,每个索引值都可以单独拆分:

     String str2 = arr[0]; // str2 = -2x^2; // split with x and get vale at index 0 
  String polynomial= "-2x^2+3x^1+6"; String[] parts = polynomial.split("x\\^\\d+\\+?"); for (String part : parts) { System.out.println(part); } 

这应该工作。 样本输出

 polynomial= "-2x^2+3x^1+6" Output: -2 3 6 polynomial = "-30x^6+20x^3+3" Output: -30 20 3