如何在USING SPLIT后更改RichTextBox上的确定字符串的字体颜色

时间:2013-03-11 11:32:15

标签: c# visual-studio-2010

Hello Master / Programmer 我正在尝试使用Split(),在使用它之后,我想检查RTB上的输入==我的点然后在RTB上更改字体颜色。就像这个例子一样。

RTB上的

INPUT:Chelsea is my favorite football club. I like playing football
我的观点:football.

然后我拆分输入,然后检查arr每个索引的拆分结果 最后,找到了ex: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

1 个答案:

答案 0 :(得分: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;
}