C# – Remove characters from C# string

cnet

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"

Best Answer

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());