如何从字符串中间有效地修剪选定的字符?

Mei*_*lon 0 .net c# string performance

任何人都可以想到一种有效的方法(时间明智)从字符串中间修剪几个选定的字符?

我想出的最好的是:

public static string Trim(this string word, IEnumerable<char> selectedChars)
{
    string result = word;
    foreach (char c in selectedChars)
        result = result.Replace(c.ToString(), "");
    return result;
}
Run Code Online (Sandbox Code Playgroud)

但它仍然太慢.

Jon*_*eet 6

我想到两个选择:

  • 使用StringBuilder
  • 使用正则表达式

这是StringBuilder版本:

public static string Trim(this string word, IEnumerable<char> selectedChars)
{
    // The best form for this will depend largely on the size of selectedChars
    // If you can change how you call the method, there are optimisations you
    // could do here
    HashSet<char> charSet = new HashSet<char>(selectedChars);

    // Give enough capacity for the whole word. Could be too much,
    // but definitely won't be too little
    StringBuilder builder = new StringBuilder(word.Length);

    foreach (char c in word)
    {
        if (!charSet.Contains(c))
        {
            builder.Append(c);
        }
    }
    return builder.ToString();
}
Run Code Online (Sandbox Code Playgroud)

如果你想要修剪一组固定的字符,那么正则表达式选项可能非常有效,并且可以构建一次正则表达式.

就像是:

// Put this statically somewhere
Regex unwantedChars = new Regex("[def]", RegexOptions.Compiled);

// Then do this every time you need to use it:
word = unwantedChars.Replace(word, "");
Run Code Online (Sandbox Code Playgroud)