Apr 07 2006
Apr 07 2006
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 ")".
Update [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
1 public string Emotify(string inputText) 2 { 3 #region Create Emote hashtable 4 Hashtable htEmotes = new System.Collections.Hashtable(100); 5 htEmotes.Add(":))", "21"); 6 htEmotes.Add(":)>-", "67"); 7 htEmotes.Add(":)", "1"); 8 htEmotes.Add(":-)", "1"); 9 htEmotes.Add(":((", "20"); 10 htEmotes.Add(":(", "2"); 11 // Add other Yahoo emotes 12 #endregion 13 14 15 StringBuilder sb = new StringBuilder(inputText.Length); 16 17 for (int i = 0; i < inputText.Length; i++) { 18 string strEmote = string.Empty; 19 foreach (string emote in htEmotes.Keys) { 20 if (inputText.Length - i >= emote.Length && 21 emote.Equals(inputText.Substring(i, emote.Length), 22 StringComparison.InvariantCultureIgnoreCase)) { 23 24 strEmote = emote; 25 break; 26 } 27 } 28 29 if (strEmote.Length != 0) { 30 sb.AppendFormat("<img src='images/{0}.gif' alt='{1}' />", 31 htEmotes[strEmote], strEmote); 32 i += strEmote.Length - 1; 33 } 34 else { 35 sb.Append(inputText[i]); 36 } 37 } 38 return sb.ToString(); 39 }