The string
class is immutable (although a reference type), hence all its static methods are designed to return a new string
variable. Calling someString.Replace
without assigning it to anything will not have any effect in your program. - Seems like you fixed this problem.
The main issue with your suggested algorithm is that it repeatedly assigning many new string
variables, potentially causing a big performance hit. LINQ doesn't really help things here. (I doesn't make the code significantly shorter and certainly not any more readable, in my opinion.)
Try the following extension method. The key is the use of StringBuilder
, which means only one block of memory is assigned for the result during execution.
private static readonly HashSet<char> badChars =
new HashSet<char> { '!', '@', '#', '$', '%', '_' };
public static string CleanString(this string str)
{
var result = new StringBuilder(str.Length);
for (int i = 0; i < str.Length; i++)
{
if (!badChars.Contains(str[i]))
result.Append(str[i]);
}
return result.ToString();
}
This algorithm also makes use of the .NET 3.5 'HashSet' class to give O(1)
look up time for detecting a bad char. This makes the overall algorithm O(n)
rather than the O(nm)
of your posted one (m
being the number of bad chars); it also is lot a better with memory usage, as explained above.