Tuesday, June 07, 2005

Removing Special Characters from .NET Strings

I came across a need today where I couldn't find an easy method on the internet. I had strings that I wanted to turn into simple filenames by removing a list of bad characters. I would have loved to have been able to use Trim(char[]) to do this, but that only works at the beginning and ending of strings.

I'm not sure how elegant and/or efficient my solution turns out to be, but here it is for anyone googling years down the road:

public override string ToString()
string junk = "~!@#$%^&*<()+=`',.?>/\\\"";
string[] ret = _displayText.Split(junk.ToCharArray());

return string.Concat(ret);

The Split(char[]) method creates an array using the provided characters as deliminators. This effectively strips out the "junk" characters, leaving you with broken bits of your original string. The Concat on the return line brings together the broken bits into one string.