我的程序使用堆栈来检查编程语句或公式是否具有平衡括号。一切正常,除了我的生活我似乎无法找到一种方法在我按下按钮检查 Parens 时输入的同一个文本框中突出显示和不平衡的一对 Parens。
这是我的参考代码:
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; 否则标志=假;返回标志;}