My program uses stacks to check if a programming statement or a formula has balanced parenthesis. everything works except for the life of me I can't seem to find a way to Highlight and unbalanced pair of Parens in the same textbox it was entered into when I push my button to check for Parens.
Here is my code for reference:
private void btnCheckParens_Click(object sender, EventArgs e)
{
Stack leftParens = new Stack();
Stack rightParens = new Stack();
string expression = txtParens.Text;
string ch;
int indexOfParens;
for ( int i = 0; i < expression.Length; i++)
{
ch = expression.Substring(i,1);
if (isParenthesis(ch))
{
if (ch == "(")
leftParens.Push(ch);
else
rightParens.Push(ch);
}
}
if (!(leftParens.Count == rightParens.Count))
{
if (leftParens.Count > rightParens.Count)
{
indexOfParens = expression.LastIndexOf("(");
txtParens.SelectionStart = indexOfParens;
txtParens.SelectionLength = 1;
}
else
indexOfParens = expression.LastIndexOf(")");
txtParens.SelectionStart = indexOfParens;
txtParens.SelectionLength = 1;
}
else
MessageBox.Show("Number of parens are balanced!","success");
}
static bool isParenthesis(string ch) { bool flag; if ( ch == "(" || ch == ")") flag = true; else flag =false; return flag; }