【发布时间】:2013-03-14 05:36:29
【问题描述】:
我的程序使用堆栈来检查编程语句或公式是否具有平衡括号。一切正常,除了我的生活我似乎无法找到一种方法在我按下按钮检查 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) { 布尔标志; 如果 ( ch == "(" || ch == ")") 标志=真; 别的 标志=假; 返回标志; }
【问题讨论】:
-
你可能会在这里找到答案stackoverflow.com/questions/1380610/…
-
那么,究竟哪一部分不工作?您检测到括号的部分,还是您在文本框中突出显示/选择字符的部分?
-
您的意图是在文本框中突出显示一个字符是吗?你有要突出显示的字符或其索引吗?
-
首先使用 txtParens.Focus() 将焦点设置到文本框;
-
不工作的部分是我在文本框中突出显示/选择字符的部分。我有角色的索引。
标签: c# .net winforms textbox selection