Remove non-alphanumeric characters from a string in C#

 In this article, we will see how to Remove non-alphanumeric characters from a string in C#

1.     

  1.               Using Regular Expression

















private static void RemoveNoAlphaChar() { string str = "dotnetoffice16@gmail.com"; str = Regex.Replace(str, "[^a-zA-Z0-9]", String.Empty); Console.WriteLine(str); Console.ReadLine(); }



Code language: C# (cs)

the output will be like below, which doesn't contain @ and .(dot)

dotnetoffice16gmailcom




2..      Using Array.FindAll() method

The Array.FindAll() method returns all elements of the specified sequence which satisfy a certain condition. To filter only alphanumeric characters, pass Char.IsLetterOrDigit to the FindAll() method, as below:


private static void RemoveNoAlphaChar() { string str = "dotnetoffice16@gmail.com"; str = String.Concat(Array.FindAll(str.ToCharArray(), Char.IsLetterOrDigit)); Console.WriteLine(str); Console.ReadLine(); }



















Code language: C# (cs)

1.     



3. Using LINQ

Another similar solution uses LINQ’s Where() method to filter elements of a sequence based on a condition.


private static void RemoveNoAlphaChar() { string str = "dotnetoffice16@gmail.com"; str = String.Concat(str.Where(char.IsLetterOrDigit)); Console.WriteLine(str); Console.ReadLine(); }


















Code language: C# (cs)

1.     Output



----------------------------------------------------------------------------------

Share this

Related Posts

Previous
Next Post »