Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><s>The <code>string</code> class is immutable (although a reference type), hence all its static methods are designed to return a <em>new</em> <code>string</code> variable. Calling <code>someString.Replace</code> without assigning it to anything will not have any effect in your program.</s> - Seems like you fixed this problem. </p> <p>The main issue with your suggested algorithm is that it repeatedly assigning many new <code>string</code> 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.)</p> <p>Try the following extension method. The key is the use of <code>StringBuilder</code>, which means only one block of memory is assigned for the result during execution.</p> <pre><code>private static readonly HashSet&lt;char&gt; badChars = new HashSet&lt;char&gt; { '!', '@', '#', '$', '%', '_' }; public static string CleanString(this string str) { var result = new StringBuilder(str.Length); for (int i = 0; i &lt; str.Length; i++) { if (!badChars.Contains(str[i])) result.Append(str[i]); } return result.ToString(); } </code></pre> <p>This algorithm also makes use of the .NET 3.5 'HashSet' class to give <code>O(1)</code> look up time for detecting a bad char. This makes the overall algorithm <code>O(n)</code> rather than the <code>O(nm)</code> of your posted one (<code>m</code> being the number of bad chars); it also is lot a better with memory usage, as explained above.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload