title: Most efficient way to remove special characters from string
body: <p>I want to remove all special characters from a string. Allowed characters are A-Z (uppercase or lowercase), numbers (0-9), underscore (_), or the dot sign (.).</p>
  
  <p>I have the following, it works but I suspect (I know!) it's not very efficient:</p>
  
  <pre><code>    public static string RemoveSpecialCharacters(string str)
      {
          StringBuilder sb = new StringBuilder();
          for (int i = 0; i &lt; str.Length; i++)
          {
              if ((str[i] &gt;= '0' &amp;&amp; str[i] &lt;= '9')
                  || (str[i] &gt;= 'A' &amp;&amp; str[i] &lt;= 'z'
                      || (str[i] == '.' || str[i] == '_')))
                  {
                      sb.Append(str[i]);
                  }
          }
  
          return sb.ToString();
      }
  </code></pre>
  
  <p>What is the most efficient way to do this? What would a regular expression look like, and how does it compare with normal string manipulation?</p>
  
  <p>The strings that will be cleaned will be rather short, usually between 10 and 30 characters in length.</p>