1

你好大师/程序员。
我正在尝试使用Split(),使用它后,我想检查RTB上的输入是否==我的观点,然后更改RTB上的字体颜色。像这个例子。

RTB 上的输入:Chelsea is my favorite football club. I like playing football
我的观点:football.

然后我拆分输入,然后检查 arr 每个索引的拆分结果。
最后,找到前:arr[4] and [9] = football

那么,如何在 RTB 屏幕上更改字体颜色,例如
“切尔西是我的最爱football。我喜欢打球football。”?

这是我的代码示例:

 ArrayList arrInput = new ArrayList();
 //if the input Chelsea is my favorite football club. I like playing football
 string allInput = rtbInput.Text; 

 string[] splitString = allInput.Split(new char[] { ' ', '\t', ',', '.'});

 foreach (string s in splitString)
 {
     if (s.Trim() != "")
     {      
          int selectionStart = s.ToLower().IndexOf("football");

          if (selectionStart != -1)
          {
              rtbInput.SelectionStart = selectionStart;
              rtbInput.SelectionLength = ("football").Length;
              rtbInput.SelectionColor = Color.Red;
          }
 }
 //What Next?? Im confused. We know that football on arrInput[4].ToString() and [9]
 //How to change font color on RTB screen when the input == football
4

1 回答 1

0

您需要选择football并设置SelectionColor属性

foreach (string s in splitString)
{
    string trimmedS = s.Trim();

    if (trimmedS != "")
    {
        int selectionStart = -1;
        if (trimmedS.ToLower == "football") // Find the string you want to color
            selectionStart = allInput.Count;

        allInput.Add(s);

        if (selectionStart != -1)
        {
            rtbInput.SelectionStart = selectionStart; // Select that string on your RTB
            rtbInput.SelectionLength = trimmedS.Length;
            rtbInput.SelectionColor = myCustomColor; // Set your color here
        }
    }
}

编辑:
替代

// create your allInput first

int selectionStart = allInput.ToLower().IndexOf("football");
if (selectionStart != -1)
{
    rtbInput.SelectionStart = selectionStart;
    rtbInput.SelectionLength = ("football").Length;
    rtbInput.SelectionColor = myCustomColor;
}

我推荐第二个答案,因为我不确定颜色是否会保留,因为我们继续构建RichTextBox.Text

Edit2:
另一种选择

// create your allInput first

Regex regex = new Regex("football", RegexOptions.IgnoreCase); // using System.Text.RegularExpressions;

foreach (Match match in regex.Matches(allInput))
{
    rtbInput.SelectionStart = match.Index;
    rtbInput.SelectionLength = match.Length;
    rtbInput.SelectionColor = myCustomColor;
}
于 2013-03-11T11:47:07.377 回答