Hello Master / Programmer.
I'm trying to use Split(), after using it, i wanna check if the input on RTB == my point then change font color on RTB. Like this example.
INPUT on RTB : Chelsea is my favorite football club. I like playing football
Chelsea is my favorite football club. I like playing football
My point : football.
Then I split the input, then i check the result of split in arr each index.
Finally, found ex : arr[4] and [9] = football
Then, how to change font color on RTB screen like
"Chelsea is my favorite . I like playing club."? 。我喜欢踢俱乐部。”?
This my code example :
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
You'll need to select football
and set the SelectionColor
property
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
}
}
}
Edit:
Alternative
// create your allInput first
int selectionStart = allInput.ToLower().IndexOf("football");
if (selectionStart != -1)
{
rtbInput.SelectionStart = selectionStart;
rtbInput.SelectionLength = ("football").Length;
rtbInput.SelectionColor = myCustomColor;
}
I recommend this second answer, because I'm not sure, whether the color will remain or not, as we continue building the RichTextBox.Text
Edit2:
Yet another alternative
// 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.