-4

我有以下字符串:

10-5*tan(40)-cos(0)-40*sin(90);

我已经提取了数学函数并计算了它们的值:

tan(40) = 1.42;
cos(0) = 1;
sin(90) = 0;

我想将这些值插入到表达式字符串中,如下所示:

10-5*(1.42)-(1)-40*(0);

请协助

4

1 回答 1

1

我会使用 Regex.Replace 然后使用自定义 MatchEvaluator 转换您的值并插入这些值,检查: http: //msdn.microsoft.com/en-us/library/cft8645c (v=vs.110).aspx

这看起来像:

class Program
{
    static string ConvertMathFunc(Match m)
    {
        Console.WriteLine(m.Groups["mathfunc"]);
        Console.WriteLine(m.Groups["argument"]);

        double arg;
        if (!double.TryParse(m.Groups["argument"].Value, out arg))
            throw new Exception(String.Format("Math function argument could not be parsed to double", m.Groups["argument"].Value));

        switch (m.Groups["mathfunc"].Value)
        {
            case "tan": return Math.Tan(arg).ToString();
            case "cos": return Math.Cos(arg).ToString();
            case "sin": return Math.Sin(arg).ToString();
            default:
                throw new Exception(String.Format("Unknown math function '{0}'", m.Groups["mathfunc"].Value));
        }
    }

    static void Main(string[] args)
    {
        string input = "10 - 5 * tan(40) - cos(0) - 40 * sin(90);";

        Regex pattern = new Regex(@"(?<mathfunc>(tan|cos|sin))\((?<argument>[0-9]+)\)");
        string output = pattern.Replace(input, new MatchEvaluator(Program.ConvertMathFunc));

        Console.WriteLine(output);
    }
}
于 2012-08-08T08:51:07.647 回答