2009-07-24 57 views
0

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

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; 
     } 




    } 
} 
+0

我不明白,y为这个问题倒投票? – Learner 2009-07-24 12:46:30

+0

我在这里做了类似的事情:www.twipler.com/experiment源代码链接在页面底部。 – 2009-07-24 12:50:00

回答

0

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

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

+0

yaa..I首先要编写基本代码,然后我将扩展到您提到的案例 – Learner 2009-07-24 12:51:20

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); 
} 
相关问题