Wednesday, July 6, 2011

Remove characters from a Numeric String

facing issues to know how do we remove characters from a String?

Consider the following example for mobile number cleanup, Take a textbox on the form

Rename it to ="TxtMobile"

Add a label and rename it to"LblResult"

Add a label and rename it to "CmdSubmit"

Declare a public string

Public Mobile As String

Under "CmdSubmit" click write the following code:

Protected Sub CmdSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CmdSubmit.Click

If Not TxtMobile.Text = "" Then

LblResult.Text = ""

Mobile = TxtMobile.Text


Lblresult.Text = Mobile


Label1.Text = "Enter Mobile Number with some characters"

End If

End SubThe above code assigns textbox value to public string we have declare above and passes it to sub CheckforChars(), Then the results are shown in Lblrsult.

Aslo write two small functions to remove characters from string of numeric

The below functions removes all the digits or numeric values from a string and stores all the chacters

Public Shared Function RemoveDigits(ByVal key As String) As String

Return Regex.Replace(key, "\d", "")

End Function

The Mobile number with characters is passed through the above function in the below sub and returned value from the above function is stored in a string called Value1

The characters present in Mobile number are replaced with nothing, you can also use .remove here instead of replace

Private Sub CheckforChars()

Dim value1 As String = RemoveDigits(Mobile)

Mobile = Mobile.Replace(value1, "")

End Sub

No comments:

Post a Comment