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

问题描述:

Hello Master/Programmer。
我想使用Split(),使用它之后,我想检查RTB上的输入==我的点然后更改RTB上的字体颜色。就像这个例子。上RTB如何在使用分割后更改RichTextBox上的确定字符串的字体颜色

INPUT: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 
+0

是什么“RTB屏幕”?甚至没有[Wikipedia](http://en.wikipedia.org/wiki/RTB#Technology)知道... – 2013-03-11 11:34:02

+0

@RB我猜RTB代表'RichTextBox' – Nolonar 2013-03-11 11:35:02

+0

@Nolonar啊!这就说得通了。我应该想到... – 2013-03-11 11:39:47

你需要选择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; 
} 
+0

@Nolonar爵士,我尝试过,但它只适用于第一个足球。就像输入:切尔西是最喜欢的“足球”。 我不为下一个足球词语工作,比如“切尔西是我最喜欢的”足球俱乐部“,我喜欢踢足球” – 2013-03-11 13:19:15

+0

@BerryHarahap我增加了另一种替代解决方案,支持多场比赛。 PS:一旦完成了所有子串的着色('rtbInput.SelectionLength = 0'),你总是可以清除选择。 – Nolonar 2013-03-11 14:05:46

+0

Dear @Nolonar .. Thansk很多。 :) :) :)干杯 – 2013-03-11 15:09:44