【问题标题】:How can I efficiently trim selected characters from middle of a string?如何有效地从字符串中间修剪选定的字符?
【发布时间】:2009-03-04 19:24:54
【问题描述】:

谁能想到一种有效的方法(时间方面)从字符串中间修剪几个选定的字符?

我想到的最好的是:

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

但还是太慢了。

【问题讨论】:

    标签: c# .net performance string


    【解决方案1】:

    我想到了两个选项:

    • 使用 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】:

      首先使用 StringBuilder 而不是字符串来替换...
      http://blogs.msdn.com/charlie/archive/2006/10/11/Optimizing-C_2300_-String-Performance.aspx

      【讨论】:

        猜你喜欢
        • 2014-11-27
        • 1970-01-01
        • 2022-11-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-07
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多