using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Collections.Generic;
string input = "Whether article $:bye: spirits X(X(X( new $:007: her covered hastily sitting her. Money $:007: witty books nor son add. Chicken $:sleepy: age had evening X(X(X(X( believe $:sleepy:$:sad: but proceed pretend mrs. At missed $:sad:$:sad: advice %) my it no sister. Miss told ham dull$:WOW: knew see she spot*IN LOVE* near can. Spirit $:adorable: her entire her 8)8)8) called.";
"$:bye:", "$:hello:", "$:007:", "$:confused:", "$:sleepy:", "$:geeky:", "$:sad:", "$:funny:",
"$:serious:", "$:explicit:", "$:angel:", "$:angry:", "$:sob:", "$:sick:", "$:devil:", ":D",
"$:cry:", "$:yay:", "$:loopy:", "$:WOW:", "$:love:", "$:doh:", ":'(", ":(", ":*", "$:oops:",
"$:kiss:", "%)", "$:OMG:", "8)", "$:festive:", "$:grumpy:", "$:no:", "$:tipsy:", "$:bored:",
":|", ":)", ":P", "$:flirty:", "$:smile:", "X(", ";)", "*IN LOVE*", "$:adorable:"
string[] tagsKeywords = { "<dnt>", "</dnt>" };
var stopwatchWrap = Stopwatch.StartNew();
var wrappedText = WrapKeywordsWithXmlTags(input, keywords);
var stopwatchRemove = Stopwatch.StartNew();
var result = RemoveTags(wrappedText, tagsKeywords);
Console.WriteLine($" Wrap Elapsed Time: {stopwatchWrap.ElapsedMilliseconds} ms");
Console.WriteLine($" Remove Elapsed Time: {stopwatchRemove.ElapsedMilliseconds} ms");
Console.WriteLine($"WrappedText: {wrappedText}");
Console.WriteLine($"Result: {result}");
static string WrapKeywordsWithXmlTags(string input, string[] keywords)
var sb = new StringBuilder(input);
var sortedDictionary = new SortedDictionary<int, string>(new ReverseIntComparer());
foreach (var keyword in keywords)
var keywordLength = keyword.Length;
while ((startIndex = input.IndexOf(keyword, startIndex, StringComparison.Ordinal)) != -1)
sortedDictionary.Add(startIndex, keyword);
startIndex += keywordLength;
foreach (var pair in sortedDictionary)
sb.Replace(pair.Value, $"<dnt>{pair.Value}</dnt>", pair.Key, pair.Value.Length);
static string RemoveTags(string input, string[] keywords)
var sb = new StringBuilder(input);
var sortedDictionary = new SortedDictionary<int, string>(new ReverseIntComparer());
foreach (var keyword in keywords)
var keywordLength = keyword.Length;
while ((startIndex = input.IndexOf(keyword, startIndex, StringComparison.Ordinal)) != -1)
sortedDictionary.Add(startIndex, keyword);
startIndex += keywordLength;
foreach (var pair in sortedDictionary)
sb.Replace(pair.Value, "", pair.Key, pair.Value.Length);
class ReverseIntComparer : IComparer<int>
public int Compare(int x, int y)