代码之家  ›  专栏  ›  技术社区  ›  Meidan Alon

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

  •  0
  • Meidan Alon  · 技术社区  · 17 年前

    我想到的最好的办法是:

    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 回复  |  直到 17 年前
        1
  •  6
  •   Jon Skeet    17 年前

    我想到了两个选择:

    • 使用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, "");
    
        2
  •  0
  •   Dror Big McLargeHuge    17 年前

    首先使用StringBuilder not string进行替换。。。
    看见 http://blogs.msdn.com/charlie/archive/2006/10/11/Optimizing-C_2300_-String-Performance.aspx