Removing Characters other than letters or numbers

  • Thread starter Thread starter Yosh
  • Start date Start date
Y

Yosh

I have a string where I want to remove only those characters that are
letters or numbers. Does .NET provide an easy method to do this?

TIA!
 
char.IsLetterOrDigit if what you want, looping through the string e.g.

for (int i=0;i < str.Length;i++)
{
if ( !char.IsLetterOrDigit(str) )
// Code here
}
 
I have a string where I want to remove only those characters that are
letters or numbers. Does .NET provide an easy method to do this?

TIA!

Regex.Replace would work best for this... Function prototype is:

[C#]
public static string Replace (
string input,
string pattern,
string replacement
)

Example:

string newString;
newString = Regex.Replace(inputString, "[a-zA-Z0-9]", string.Empty);

-mdb
 
Try using a Regular Expression. That's the easiest way.

public string StripLettersAndNumbers(string input)
{
System.Text.RegularExpressions.Regex regex = new
System.Text.RegularExpressions.Regex("[A-Z0-9]",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
return regex.Replace(input, String.Empty);
}
 
john said:
char.IsLetterOrDigit if what you want, looping through the string e.g.

for (int i=0;i < str.Length;i++)
{
if ( !char.IsLetterOrDigit(str) )
// Code here
}


Or even nicer:

foreach (char c in str)
{
if (char.IsLetterOrDigit(c))
{
...
}
}

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top