有人能想出一种有效的方法(时间明智)从字符串中间修剪一些选定的字符吗?
我想出的最好的是:
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;
}
但它仍然太慢了。
答案 0 :(得分:6)
有两种选择:
这是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)
首先使用StringBuilder而不是替换字符串...
见http://blogs.msdn.com/charlie/archive/2006/10/11/Optimizing-C_2300_-String-Performance.aspx