I’m working on a search function for an MVC C# app that will place a (possibly large) chunk of text through a filter, and given the search query, will place an html <span> with a highlighted style before and after each search term.
I’ve got a simple algorithm working, but I’ve got a feeling it will be slow, probably because of the amount of strings that will need to be created (2 * the number of matches).
public static string Surround(string original, string head, string tail, string match, StringComparison comparer) { var ret = original; if (ret.IndexOf(match, 0, comparer) != -1) { var lastIndex = 0; while ((lastIndex = ret.IndexOf(match, lastIndex, comparer)) != -1) { ret = ret.Insert(lastIndex, head); var tailIndex = lastIndex + match.Length + head.Length; lastIndex = tailIndex; ret = ret.Insert(tailIndex, tail); } } return ret; }
I’m wondering if anyone can give some hints for a better algorithm that would perform better for large chunks of text? I was thinking of using a stringbuilder, but it’s also occurred to me that I could be approaching this from entirely the wrong way. Any insight would be greatly appreciated.
A regular expression will do the job, and the code should be a lot simpler. However you’d need to test to determine if it actually delivers better performance. Something like this:
Even better if you can pass in the replacer whole as you save 2N string concats: