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

String remove non numeric characters
The following asp.net c# example code demonstrate us how can we remove non numeric characters from a string object programmatically at run time in an asp.net application. .Net framework's String Class represents text as a series of Unicode characters.

To remove non numeric characters from a string, first we need to convert the string object to a Char Array. String.ToChartArray() method allow us to copies the characters in this instance to a Unicode character array. Next, we loop through the char array elements by using foreach loop.

Then we test which character is numeric or not. Char.IsDigit(Char) overloaded method indicate whether the specified Unicode character is categorized as a decimal digit. So we can remove all non numeric characters from string and can keep only numeric characters (0 to 9) by using Chart.IsDigit(Char) method.

<%@ 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.0F*30JG7O9";

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

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

        //make string empty now.
        characters = "";
        foreach(char c in chars)
            //if (char.IsNumber(c))
            if (char.IsDigit(c))
                Label1.Text += c.ToString();
                characters += c;
                Label1.Text += "non numeric character";
            Label1.Text += "<br />";

        Label1.Text += "<br />after removing non 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 numeric characters</title>  
    <form id="form1" runat="server">  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string remove non numeric characters
        <hr width="550" align="left" color="Gainsboro" />  
        <br /><br />
            Text="string remove non numeric characters"  
More c# examples