327

I want to remove all special characters from a string. Allowed characters are A-Z (uppercase or lowercase), numbers (0-9), underscore (_), or the dot sign (.).

I have the following, it works but I suspect (I know!) it's not very efficient:

 public static string RemoveSpecialCharacters(string str) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.Length; i++) { if ((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'A' && str[i] <= 'z' || (str[i] == '.' || str[i] == '_'))) { sb.Append(str[i]); } } return sb.ToString(); } 

What is the most efficient way to do this? What would a regular expression look like, and how does it compare with normal string manipulation?

The strings that will be cleaned will be rather short, usually between 10 and 30 characters in length.

8
  • 5
    I won't put this in an answer since it won't be any more efficient, but there are a number of static char methods like char.IsLetterOrDigit() that you could use in your if statement to make it more legible at least. Commented Jul 13, 2009 at 15:40
  • 5
    I'm not sure that checking for A to z is safe, in that it brings in 6 characters that aren't alphabetical, only one of which is desired (underbar). Commented Jul 13, 2009 at 15:41
  • 4
    Focus on making your code more readable. unless you are doing this in a loop like 500 times a second, the efficiency isn't a big deal. Use a regexp and it will be much easier to read.l Commented Jul 13, 2009 at 15:42
  • 5
    Byron, you're probably right about needing to emphasize readability. However, I'm skeptical about regexp being readable. :-) Commented Jul 13, 2009 at 15:45
  • 2
    Regular expressions being readable or not is kind of like German being readable or not; it depends on if you know it or not (although in both cases you will every now and then come across grammatical rules that make no sense ;) Commented Jul 13, 2009 at 15:50

31 Answers 31

1
2
-3

Simple way with LINQ

string text = "123a22 "; var newText = String.Join(string.Empty, text.Where(x => x != 'a')); 
Sign up to request clarification or add additional context in comments.

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.