Friday, 10 May 2013

Replace all special characters in c# from string

Solution 1 : 
using System.Text.RegularExpressions;
public string RemoveSpecialCharacters(string str)
{
    return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}

Solution 2 :

public string RemoveSpecialChars(string str)
{
    string[] chars = new string[] { ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "'", "\"", ";","_","(", ")", ":", "|", "[", "]" };

  for (int i = 0; i< chars.Lenght; i++)
  {
if (str.Contains(chars[i]))
{
str = str.Replace(chars[i],"");
}
   }
return str;
}

No comments:

Post a Comment

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...