How to Remove all the special characters from a Given String

Hi,

Some times we require to remove all the existing special characters in a string. The same we can done using the following code.


public string RemoveSpecialChars(string str)
{
string[] chars = new string[]{",",".","/","!","@","#","$","%","^","&","*","'","\"",";","-","_","(",")",":","|","[","]"};
for(int i = 0; i< chars.Length; i++ )
{
if(str.Contains(chars[i]))
{
str = str.Replace(chars[i],"");
}
}
return str;
}

string newString = RemoveSpecialChars("T!h^e%c!od#e&i's#s;u$b%m|i%t(te)d by M[o:h]i)t@Ja*i}n");


Comments

Guest Author: Felipe Volpatto25 Jun 2012

Not a good solution. I prefer regular expressions.

Author: Phagu Mahato25 Jan 2014 Member Level: Gold   Points : 6

You can use given code snippet for Remove all the special characters from a Given String


[1] Finding Special Character
public static string Slugify(string phrase)
{
String str = Regex.Replace(phrase, @"[^a-z0-9\s-]", " ");
str = Regex.Replace(str, @"\s+", " ").Trim();
return str;
}

For Replace Special Characters

public static string RemoveSpeCharacter(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}


protected void Button1_Click(object sender, EventArgs e)
{
string str=TextBox1.Text;
TextBox2.Text=RemoveSpelCharacter(str);
}
Or
using System;
using System.Text.RegularExpressions;

namespace eApplication3
{
class Program
{
static void Main(string[] args)
{
string str = "DotNet@Spider.com";
string replacestr= Regex.Replace(str, "[^a-zA-Z0-9_]+", " ");
Console.WriteLine(replacestr);
Console.ReadLine();
}
}
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: