c# how to remove special characters from string code example

Example 1: c# remove specific character from string

string phrase = "this is, a string with, too many commas";
phrase = phrase.Replace(",", "");

Example 2: c# string remove special characters

public static string RemoveSpecialCharacters(this string str) {
   StringBuilder sb = new StringBuilder();
   foreach (char c in str) {
      if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_') {
         sb.Append(c);
      }
   }
   return sb.ToString();
}