任何人都可以想到一种有效的方法(时间明智)从字符串中间修剪几个选定的字符?
我想出的最好的是:
public static string Trim(this string word, IEnumerableselectedChars) { string result = word; foreach (char c in selectedChars) result = result.Replace(c.ToString(), ""); return result; }
但它仍然太慢.
我想到两个选择:
使用StringBuilder
使用正则表达式
这是StringBuilder
版本:
public static string Trim(this string word, IEnumerableselectedChars) { // 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 charSet = new HashSet (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, "");