471,319 Members | 1,344 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,319 software developers and data experts.

Removing Characters other than letters or numbers

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!

Jan 11 '06 #1
4 4114
char.IsLetterOrDigit if what you want, looping through the string e.g.

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

Jan 11 '06 #2
"Yosh" <yo***@nospam.com> wrote in news:u4vrznsFGHA.3912
@TK2MSFTNGP10.phx.gbl:
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
Jan 11 '06 #3
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.Ignore Case);
return regex.Replace(input, String.Empty);
}

Jan 11 '06 #4
john doe wrote:
char.IsLetterOrDigit if what you want, looping through the string e.g.

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


Or even nicer:

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

Jon

Jan 11 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

23 posts views Thread by Peter Row | last post: by
19 posts views Thread by many_years_after | last post: by
3 posts views Thread by Julien | last post: by
4 posts views Thread by Ahmed, Shakir | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.