使用索引器从字符串中获取2个字符的问题

时间:2009-07-24 12:42:49

标签: c#-3.0

我在阅读char值时面临一个问题。 请参阅下面的程序。我想评估一个中缀表达式 你可以看到我想读'10','*','20'然后使用它们......但是如果我使用字符串索引器s [0]将是'1'而不是'10'因此我是无法获得预期的结果。 你们能给我一些建议吗?代码在c#

class Program
    {
        static void Main(string[] args)
        {
            string infix = "10*2+20-20+3";
            float result = EvaluateInfix(infix);
            Console.WriteLine(result);
            Console.ReadKey();

        }

        public static float EvaluateInfix(string s)
        {
            Stack<float> operand = new Stack<float>();
            Stack<char> operator1 = new Stack<char>();
            int len = s.Length;
            for (int i = 0; i < len; i++)
            {
                if (isOperator(s[i]))  // I am having an issue here as s[i] gives each character and I want the number 10 
                    operator1.Push(s[i]);
                else
                {
                    operand.Push(s[i]);
                    if (operand.Count == 2)
                        Compute(operand, operator1);
                }
            }

            return operand.Pop();


        }

        public static void Compute(Stack<float> operand, Stack<char> operator1)
        {
            float operand1 = operand.Pop();
            float operand2 = operand.Pop();
            char op = operator1.Pop();

            if (op == '+')
                operand.Push(operand1 + operand2);
            else
                if(op=='-')
                    operand.Push(operand1 - operand2);
                else
                    if(op=='*')
                        operand.Push(operand1 * operand2);
                    else
                        if(op=='/')
                            operand.Push(operand1 / operand2);
        }




        public static bool isOperator(char c)
        {
            bool result = false;
            if (c == '+' || c == '-' || c == '*' || c == '/')
                result = true;
            return result;
        }




    }
}

2 个答案:

答案 0 :(得分:0)

您需要拆分字符串 - 这意味着要准确地 分割字符串。在这种情况下,我怀疑你会发现Regex.Split是最合适的分割工具,因为你正在处理模式。或者,您可能想要编写自己的拆分例程。

你只需要处理整数和运算符吗?空白怎么样?括号?领先的负数?乘数乘以(例如“3 * -5”)?

答案 1 :(得分:0)

将数值存储在变量中,并在遇到运算符或字符串结尾时将其推送:

int num = 0;
foreach (char c in s) {
   if (isOperator(c)) {
      if (num != 0) {
         operand.Push(num);
         num = 0;
      }
      operator1.Push(c);
      if (operand.Count == 2) {
         Compute(operand, operator1);
      }
   } else {
      num = num * 10 + (int)(c - '0');
   }
}
if (num != 0) {
   operand.Push(num);
}