Wednesday, September 7, 2011

Remove Special Characters from the String

You can remove the special character by comparing character by character; otherwise you can use Regex Class. By using Regex class, instead of remove the character we can mention what character that string should contain.  I have created a method that wills the return the string without any special character.

VB.NET

Namespace required: Imports System.Text.RegularExpressions

Public Function RemoveSpecialCharacter(ByVal str As String)

  Dim strresult As String = ""
  strresult =Regex.Replace(str, "[^A-Z,0-9,a-z]", "")
  Return strresult

End Function

C#

Namespace required: using System.Text.RegularExpressions ; 

public string RemoveSpecialCharacter(string str)
{
  string strresult = "";
  strresult =Regex.Replace (str,"[^A-Z,0-9,a-z]","");
  return strresult;
}

Note : I am Added alphanumeric characters only. If you want add to any other like / or \ you can add to the expression

I hope this article will be very helpful to all. Thanks for reading this article.

“Keep reading and share the knowledge”  
“Grow more trees to save the Earth”

No comments:

Post a Comment