OriginalGriff's answer above is an elegant solution to finding matches, and their indexes, and you can use that code to then go through the content inserted in an RTF Control and replace the matches with the appropriate bitmap/Gif Smiley image.
If you want to just get busy replacing the RTF, without the formal step of pre-calculating matches, and indexes, then you could use another strategy, such as this WinForms code:
1. "bind" all your Smiley/images into Resources in your .NET app. Or you could put them in an ImageList.
2. create a Dictionary of the form Dictionary<string,image> that will hold the string representations of the Smileys as Keys, and a link to the Smiley image resources as Values. So, at some point, you'll build-out the Dictionary, Smiley by Smiley, in a loop, or item-by-item, like this:
using YourRichTextApp.Properties;
EmoticonDict.Add(":)", MyChatApp.Properties.Resources.Smiley_Smile);
Then you simply iterate through all the Keys in your Dictionary, and use an internal 'while loop to keep replacing every instance of the text in each Key with the image.
Do the replacement by copying the image to the Clipboard before the start of the 'while loop, and pasting it in every time you need to.
So, you'll can use something like this:
rtfText = RTFTextBox.Text;
foreach(string theKey in EmoticonDict.Keys)
{
Clipboard.SetImage(EmoticonDict[theKey]);
while (rtfText.Contains(theKey))
{
emoticonIndex = rtfText.IndexOf(theKey);
rtfText = rtfText.Remove(emoticonIndex, theKey.Length);
RTFTextBox.Select(emoticonIndex, theKey.Length);
RTFTextBox.Paste();
rtfText = RTFTextBox.Text;
}
Clipboard.Clear();
}
Acknowledgement: this code has been adapted by me from code originally posted by Krishan Galore in 2012 [
^].
Krishan used a HashTable, and I use a Dictionary for creating string/image KeyValuePairs. Using a Dictionary eliminates the need to cast to Type Image that using a HashTable requires.
I eliminated loading the Clipboard with the Emoticon image each time the 'while loop is executed.
I have "fixed" a problem with that code: it does not properly clear the emoticon-string.
Note that you could use this code to replace any arbitrary string with any arbitrary picture resource.