-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 に答える