首页 > 解决方案 > 如何替换字符串中的“x”并等同于数字?

问题描述

给定一个只有数字、数学运算符和“x”的字符串,以及一个替换 x 的数字,你将如何替换字符串中的所有 x,然后将字符串等同于答案?到目前为止,我是这样的:

String str = "2+4x"; //Example string, could be [2 +4x -  5/ 4 - 9( 6+1*x)] or [4x+0]
Float numToReplace = 20.4; //Has to be Float, cannot use Double


str = str.replace("x", numToReplace);

// How to simplify the string into a number?

我无法使字符串相等,也无法弄清楚如何摆脱“隐含乘法”(当用户输入“2x”时,我想将其更改为(2 * x)以使等式起作用更换 x) 后正确。

标签: javaequation

解决方案


  1. 替换x数字后
  2. 替换独立x
String str = "2+4x * x";
float numToReplace = 20.4f;

String expr = str
    .replaceAll("(\\d+)x", "$1 * " + numToReplace)
    .replaceAll("x", Float.toString(numToReplace);

可以使用 Nashorn 脚本引擎评估生成的表达式,但它已被弃用:

public static void main(String ... args) throws ScriptException {
    String str = "2+4x * x";
    float numToReplace = 20.4f;

    String expr = str
        .replaceAll("(\\d+)x", "$1 * " + numToReplace)
        .replaceAll("x", Float.toString(numToReplace);

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");

    // a checked ScriptException may be thrown
    System.out.println(expr + " = " + engine.eval(expr));

    float result = Float.parseFloat(engine.eval(expr));
    System.out.println("result = " + result);
}

输出展示了著名的浮点功能:

2+4 * 20.4 * 20.4 = 1666.6399999999999
result = 1666.64

推荐阅读