C#多次递增

时间:2017-11-16 19:04:48

标签: c#

我有,为我做的代码" x + y = z"

if (command.Contains("+")) // string polecenie = "";'
{
    polecenie = "{" + command + ")";
    polecenie = polecenie.Replace("+", "}(");
    double a = Convert.ToDouble(Between(polecenie, "{", "}"));
    double b = Convert.ToDouble(Between(polecenie, "(", ")"));
    double wyn = a + b;
    richTextBox1.Text += a + " + " + b + " is " + wyn + "\r\n";
}

当'命令'是" 4 + 5"," 3 + 4"或类似这样的代码有效,但当我尝试做#34; 4 + 3 + 23"它不起作用。带有起始'命令的最终字符串' " 4 + 5 + 6&#34 ;, polecenie是:" {4}(5)(6)" ...介于方法之间:

public string Between(string content, string First, string Last)
{
    string end = "";
    int Plc1 = content.IndexOf(First) + First.Length;
    int Plc2 = content.IndexOf(Last);
    end = content.Substring(Plc1, Plc2 - Plc1);
    return end;
}

我该怎么做? (我希望它可以与所有可能的添加一起使用(" 4 + 4"," 34 + 5 + 54"," 43 + 4 + 65 + 54"。 ..)

1 个答案:

答案 0 :(得分:1)

您可以使用DataTable对象不重新发明轮子。

richTextBox1.Text = string.Format("{0} is {1}\r\n", command,
    (new System.Data.DataTable()).Compute(command, string.Empty));

这将支持+, - ,*,/和%(mod)运算符。更多信息:https://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx