Issue with getting 2 chars from string using indexer

Posted by Learner on Stack Overflow See other posts from Stack Overflow or by Learner
Published on 2009-07-24T12:42:48Z Indexed on 2010/03/25 10:03 UTC
Read the original article Hit count: 400

Filed under:

I am facing an issue in reading char values. See my program below. I want to evaluate an infix expression.
As you can see I want to read '10' , '*', '20' and then use them...but if I use string indexer s[0] will be '1' and not '10' and hence I am not able to get the expected result. Can you guys suggest me something? Code is in 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;
        }




    }
}

© Stack Overflow or respective owner

Related posts about c#3.0