簡體   English   中英

突出顯示RichTextBox C#Windows窗體中的不平衡括號

[英]Highlighting Unbalanced Parentheses in RichTextBox C# Windows Forms

我目前有一個Windows窗體設置,該窗體在RichTextBox內接受一個數學表達式,並在表達式中搜索任何不平衡的括號。 我的表單包含RichTextBox和一個顯示“檢查Parens”的按鈕。 我也在嘗試使用堆棧檢查不平衡的括號。 我想要以某種方式指出哪些括號是不平衡的。 我想通過突出顯示或加粗RichTextBox內的括號來做到這一點。 有沒有辦法用我現在設置的代碼來做到這一點? 這是我的下面代碼,任何建設性的反饋將不勝感激!

public partial class checkParentheses : Form
{
    const char leftParens = '(';
    const char rightParens = ')';

    public checkParentheses()
    {
        InitializeComponent();
    }

    public void checkParensButton_Click(object sender, EventArgs e)
    {
        int value;
        checkBalancedParens(mathEquation.Text, out value);
    }

    bool checkBalancedParens(string expression, out int error)
    {
        var parens = new Stack<int>(expression.Length);//Create stack
        error = -1; //Error at -1

        for (int i = 0; i < expression.Length; i++)//Check for unbalanced Parentheses
        {
            char p = expression[i];
            if (p == leftParens)//if p finds left parens
            {
                parens.Push(i);//push to top of stack
            }
            else if (p == rightParens)//if p finds right parens
            {
                if (parens.Count == 0)//if stack has zero items
                {
                    error = i + 1;
                    return false;
                }
                parens.Pop();//Returns to top of stack
            }
        }
        if (parens.Count > 0)//if stack has more than 0 items
        {
            error = parens.Peek() + 1; //Peek at top of stack
            MessageBox.Show("Unbalanced");
            return false;
        }
        MessageBox.Show("Balanced");//Otherwise, expression is balanced
        return true;
    }

}

編輯:給定下面的解決方案,這是次等的。 如果要加粗文本,則仍包含示例。 您可以將HighlightOffenders方法替換為

private void HighlightOffenders(IEnumerable<int> listOfIndexes)
    {

        foreach (var index in listOfIndexes.Reverse())
        {

            mathEquation.Select(index,1);
            mathEquation.SelectionFont = new Font(mathEquation.Font, FontStyle.Bold);
        }

    }

因此,您應該同時跟蹤左側paren索引和右側paren索引。 然后只需將匹配對彈出各自的堆棧即可。

至於顯示文本,我不知道這是否是最好的方法,但是這是可行的方法。 它需要重建字符串,但會將正確的結果放入RichTextBox中。 您將需要忽略我的表單稱為“ Form1”的事實,而應將其替換為“ checkParentheses”。 可能有一種方法可以在實際字符上突出顯示突出顯示的內容,但是我對此並不熟悉。

public partial class Form1 : Form
{
    const char leftParenChar = '(';
    const char rightParenChar = ')';

    public Form1()
    {
        InitializeComponent();
    }

    public void checkParensButton_Click(object sender, EventArgs e)
    {
        checkBalancedParens(mathEquation.Text);
    }

    bool checkBalancedParens(string expression)
    {
        var leftParensIndexes = new Stack<int>(expression.Length);
        var rightParensIndexes = new Stack<int>(expression.Length);
        var isError = false;


        for (int i = 0; i < expression.Length; i++)//Check for unbalanced Parentheses
        {
            char p = expression[i];
            if (p == leftParenChar)//if p finds left parens
            {
                leftParensIndexes.Push(i);//push to top of stack
            }
            else if (p == rightParenChar)//if p finds right parens
            {
                rightParensIndexes.Push(i);

                //keep a record if there is an error, but don't stop yet.
                if (leftParensIndexes.Count == 0)
                {
                    isError = true;
                }
                else
                {
                    //eliminate the matching pair if it exists
                    rightParensIndexes.Pop();
                    leftParensIndexes.Pop();
                }


            }
        }
        if (leftParensIndexes.Count > 0)//if stack has more than 0 items
        {
            isError = true;
        }
        HighlightOffenders(rightParensIndexes.Concat(leftParensIndexes));
        return !isError;
    }

    private void HighlightOffenders(IEnumerable<int> listOfIndexes)
    {
        var text = mathEquation.Text;
        mathEquation.Clear();
        int lastIndex = 0; //store the last index you finished at (for string math)
        int count = 0; //the number of items that we've added (also for string math)

        foreach (var index in listOfIndexes.Reverse())
        {

            mathEquation.AppendText(text.Substring(lastIndex, index - lastIndex - count));
            mathEquation.SelectionFont = new Font(mathEquation.Font, FontStyle.Bold);
            mathEquation.AppendText(text.Substring(index,1));
            mathEquation.SelectionFont = new Font(mathEquation.Font, FontStyle.Regular);
            lastIndex = index;
            count++;

        }
        mathEquation.AppendText(text.Substring(lastIndex + count-1, text.Length - lastIndex - count + 1));
    }
}

此處描述的在RichEdit中突出顯示文本。 完整的解決方案:

private void checkParensButton_Click(object sender, EventArgs e)
{
  // clean up previous selection
  mathEquation.SelectAll();
  mathEquation.SelectionBackColor = Color.White;

  var indexes = EnumerateUnbalancedParentheses(mathEquation.Text);
  foreach (var index in indexes)
  {
    mathEquation.Select(index, 1);
    mathEquation.SelectionBackColor = Color.Aqua;
  }
}

private static IEnumerable<int> EnumerateUnbalancedParentheses(string expression)
{
  var openingParentheses = new Stack<int>();
  var closingParentheses = new Stack<int>();

  for (var i = 0; i < expression.Length; ++i)
  {
    var symbol = expression[i];
    if (symbol == '(')
    {
      openingParentheses.Push(i);
    }
    else if (symbol == ')')
    {
      if (openingParentheses.Count > 0)
        openingParentheses.Pop();
      else
        closingParentheses.Push(i);
    }
  }

  return openingParentheses.Concat(closingParentheses);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM