Hello, I am an Engineering Manager at Facebook with 13+ years in Ad Technology, Natural Language Processing and Data mining. (Learn More)
by Pravin Paratey

Implementing Emoticons in C#

This piece of code shows you one way of replacing emoticons with their images. Remember the order of replacing the emotes matters! If you replace :) before :)), then you’ll end up with a wrong image followed by the orphan “)”.

Updates

  1. Oct 10, 2010 - A faster way (time complexity) of doing this would be to build a B-Tree and replace text in a single pass.
  2. Feb 11, 2012 - The post titled Super Quick find/replace explores faster ways of performing a find/replace.
public string Emotify(string inputText)
{
    #region Create Emote hashtable
    Hashtable htEmotes = new System.Collections.Hashtable(100);
    htEmotes.Add(":))", "21");
    htEmotes.Add(":)>-", "67");
    htEmotes.Add(":)", "1");
    htEmotes.Add(":-)", "1");
    htEmotes.Add(":((", "20");
    htEmotes.Add(":(", "2");
    // Add other Yahoo emotes
    #endregion

    StringBuilder sb = new StringBuilder(inputText.Length);

    for (int i = 0; i < inputText.Length; i++) {
        string strEmote = string.Empty;
        foreach (string emote in htEmotes.Keys) {
            if (inputText.Length - i >= emote.Length &&
                    emote.Equals(inputText.Substring(i, emote.Length),
                    StringComparison.InvariantCultureIgnoreCase)) {
                strEmote = emote;
                break;
            }
        }

        if (strEmote.Length != 0) {
            sb.AppendFormat("<img src='images/{0}.gif' alt='{1}' />", 
                htEmotes[strEmote], strEmote);
            i += strEmote.Length - 1;
        }
        else {
            sb.Append(inputText[i]);
        }
    }
    return sb.ToString();
}