もちろん状況によって異なり
ますが、テキストが長く、単語が多く、
パフォーマンスを最適化したい場合。
単語からトライを作成し、トライで一致するものを検索する必要があります。
複雑さの順序を下げることはありませんが、それでも O(nm) ですが、単語の大きなグループの場合、1 つずつではなく、各文字に対して複数の単語をチェックできます。
これを高速化するには、数百語で十分だと思います。
これは私の意見では最速の方法であり、私
はあなたが始めるための関数を書きました:
public struct FindRecord
{
public int WordIndex;
public int PositionInString;
}
public static FindRecord[] FindAll(string input, string[] words)
{
LinkedList<FindRecord> result = new LinkedList<FindRecord>();
int[] matchs = new int[words.Length];
for (int i = 0; i < input.Length; i++)
{
for (int j = 0; j < words.Length; j++)
{
if (input[i] == words[j][matchs[j]])
{
matchs[j]++;
if(matchs[j] == words[j].Length)
{
FindRecord findRecord = new FindRecord {WordIndex = j, PositionInString = i - matchs[j] + 1};
result.AddLast(findRecord);
matchs[j] = 0;
}
}
else
matchs[j] = 0;
}
}
return result.ToArray();
}
別のオプション:
正規表現がコードのビルドよりも高速になるまれなケースかもしれません。
使ってみて
public static string ReplaceAll(string input, string[] words)
{
string wordlist = string.Join("|", words);
Regex rx = new Regex(wordlist, RegexOptions.Compiled);
return rx.Replace(input, m => "");
}