如何改变字体颜色确定字符串上的RichTextBox使用分割后

本文关键字:字符串 RichTextBox 分割 何改变 改变 颜色 字体 | 更新日期: 2023-09-27 18:03:14

大师/程序员你好。
我试图使用Split(),使用它后,我想检查RTB上的输入==我的点,然后改变RTB上的字体颜色。例如:

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

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

然后,如何改变RTB屏幕上的字体颜色,如
"Chelsea is my favorite 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

如何改变字体颜色确定字符串上的RichTextBox使用分割后

您需要选择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;
}