数学方程为一个字符串

时间:2018-02-07 19:31:49

标签: c# math

如何在C#中找到以字符串形式给出的数学方程的结果? 例如:“2 + 5 * 3 + 7”应该返回3 并且“(2 + 5)*(3 + 7)”应该返回70 ...只是任何数学方程式。 我尝试根据操作符的位置将字符串拆分为Substring但是失败了。

int strStart = 0, strLength = 0, result =0, no=0;

List<char> ops = new List<char>();
        foreach (char c in inputString)
        {
            if (IsOperator(c))
            {
                strLength = inputString.IndexOf(c) - strStart;
                Console.WriteLine("String Length = " + strLength);
                if (ops.Count == 1)
                    result = Convert.ToInt32(inputString.Substring(strStart, strLength));
                else
                {                        
                    no = Convert.ToInt32(inputString.Substring(strStart, strLength));
                    result = Math(result, no, c);
                }
                strStart = strStart + strLength + 1;
            }                 

        }

no = Convert.ToInt32(inputString.Substring(strStart, strLength));
        result = Math(result, no, op);

不知怎的,我一直在搞乱strLength变量。然后我尝试了这个

List<char> operators = new List<char>();
            foreach (char c in stringValue)
            {
                 try
                 {
                    int i = Convert.ToInt32(c.ToString());
                 }
                catch
                 {
                    operators.Add(c);
                 }
            }
            int totalOperators = operators.Count;
            string[] stringValues = new string[totalOperators + 1];
            int[] indexes = new int[totalOperators];
            for(int j=0;j<totalOperators;j++)
                indexes[j] = stringValue.IndexOf(operators.ElementAt(0));
            stringValues[0] = stringValue.Substring(0, indexes[0]) ;
            for(int k=1;k<totalOperators;k++)
            {
                stringValues[k] = stringValue.Substring(indexes[k - 1], indexes[k] - indexes[k - 1]);
            }
            stringValues[totalOperators] = stringValue.Substring(indexes[totalOperators - 1], stringValue.Length- indexes[totalOperators - 1]);

            int[] intValues = new int[totalOperators + 1];
            for (int j = 0; j <= totalOperators; j++)
                intValues[j] = Convert.ToInt32(stringValues[j]);
            int result = intValues[0];
            for (int k = 0; k < totalOperators; k++)
            {
                char c = operators.ElementAt(k);
                switch (c)
                {
                    case '+':
                        result += intValues[k + 1];
                        break;

                }

            }

它添加失败,所以我甚至没有添加其他案例,请帮助我。是否有可用于简化流程的类/库?

0 个答案:

没有答案