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

时间:2009-03-04 19:24:54

标签: c# .net performance string

有人能想出一种有效的方法(时间明智)从字符串中间修剪一些选定的字符吗?

我想出的最好的是:

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;
}

但它仍然太慢了。

2 个答案:

答案 0 :(得分: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();
}

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

类似的东西:

// 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, "");

答案 1 :(得分:0)