c# - How to remove non alphanumeric characters from a string

String remove non alphanumeric
The following asp.net c# example code demonstrate us how can we remove non alphanumeric characters programmatically at run time from a string object. So, we keep only alphabet (letter) (a to z) and numeric characters (0 to 9). .Net framework's String class has no built in method or property to remove non alphanumeric characters from a string value.

To remove non alphanumeric characters from a string object, first we need to convert the string value to a char array. String.ToCharArray() copies the characters in this instance to a Unicode character array. Next, we need to loop through the char array elements. In this example, we loop char array elements by using foreach loop.

Finally, we can test, which character is alphanumeric or not. We can determine a character's alphanumeric state by using Char.IsLetterOrDigit() method. The Char.IsLetterOrDigit(Char) overloaded method indicate whether a Unicode character is categorized as a letter or a decimal digit. This way we can check each character and remove non alphanumeric character from string value.

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
        //this section create a string variable.
        string characters = "1.{-A}* 2.[B)";

        Label1.Text = "string of characters..................<br />";
        Label1.Text += characters + "<br /><br />";

        //this line convert string to char array
        char[] chars = characters.ToCharArray();

        characters = "";
        foreach(char c in chars)
            if (char.IsLetterOrDigit(c))
                Label1.Text += c.ToString();
                characters += c;
                Label1.Text += "non alphanumeric character";
            Label1.Text += "<br />";

        Label1.Text += "<br />after removing non alpha numeric characters from string...<br />";
        Label1.Text += characters;
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string remove non alphanumeric</title>  
    <form id="form1" runat="server">  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string remove non alphanumeric
        <hr width="550" align="left" color="Gainsboro" />  
        <br /><br />
            Text="string remove non alphanumeric"  
More c# examples