string expr = Text1.Text;
string[] num = Regex.Split(expr, @"\(|\)|\-|\+|\*|\/").Where(s => !String.IsNullOrEmpty(s)).ToArray(); // get Array for numbers
string[] op = Regex.Split(expr, @"\(|\)|\d{1,3}").Where(s => !String.IsNullOrEmpty(s)).ToArray(); // get Array for mathematical operators +,-,/,*
int firstVal = 0;
int numCtr = 0;
int lastVal = 0;
string lastOp = "";
int num2Cntr = 0;
foreach (string n in num)
{
numCtr++;
if (numCtr == 1)
{
lastVal = int.Parse(n);
}
else
{
if (!String.IsNullOrEmpty(lastOp))
{
switch (lastOp)
{
case "+":
lastVal = lastVal + int.Parse(n) ;
break;
case "-":
lastVal = lastVal - int.Parse(n);
break;
case "*":
lastVal = lastVal * int.Parse(n);
break;
case "/":
lastVal = lastVal / int.Parse(n);
break;
case "(":
numCtr++;
foreach (string a in num)
{
num2Cntr++;
if (num2Cntr == 1)
{
firstVal = int.Parse(a);
}
else
{
if (!String.IsNullOrEmpty(lastOp))
{
switch (lastOp)
{
case "+": firstVal = firstVal + int.Parse(a);
break;
case "-":
firstVal = firstVal - int.Parse(a);
break;
case "*":
firstVal = firstVal * int.Parse(a);
break;
case "/":
firstVal = firstVal / int.Parse(a);
break;
}
}
}
}
break;
case ")":
lastVal = lastVal + firstVal;
return;
}
}
}
int opCtr = 0;
foreach (string o in op)
{
opCtr++;
if (opCtr == numCtr)
{
lastOp = o;
break;
}
}
}
Text2.Text = lastVal.ToString();
1)How to set precedence high for parentheses? 2) I am trying to set precedence because the expression entered should evaluate as like binary tree. First it must take precedence high for parentheses and then for operators. 3) My code above works fine and evaluate expression from left to right. i.e, 5+6+7=18 but if i give 5+(5+5)+(5*2) i am getting result as 40. But exact result is 25. can any help me. thank you.