Remove characters from C# string

wanwan picture wanwan · Sep 14, 2011 · Viewed 330.7k times · Source

How might I remove characters from a string? For example: "My name @is ,Wan.;'; Wan".

I would like to remove the characters '@', ',', '.', ';', '\'' from that string so that it becomes "My name is Wan Wan"

Answer

Albin Sunnanbo picture Albin Sunnanbo · Sep 14, 2011
var str = "My name @is ,Wan.;'; Wan";
var charsToRemove = new string[] { "@", ",", ".", ";", "'" };
foreach (var c in charsToRemove)
{
    str = str.Replace(c, string.Empty);
}

But I may suggest another approach if you want to remove all non letter characters

var str = "My name @is ,Wan.;'; Wan";
str = new string((from c in str
                  where char.IsWhiteSpace(c) || char.IsLetterOrDigit(c)
                  select c
       ).ToArray());