Friday, June 27, 2008

Strip numbers from String : C# .NET Remove numbers from string

Here is a simple function I created to strip/remove numbers from a string.
I used the regular expressions to check if a char is number.
I choose to use regular expressions than using the Double.TryParse() because I feel RegEx are faster then the TryParse function. I could be wrong but at this point is doing the job.





public string StripNumbers(string input)
{
Regex regEx = new Regex("[0-9]+");
StringBuilder sb = new StringBuilder();
foreach (char a in input)
{
if (!regEx.IsMatch(a.ToString()))
{
sb.Append(a);
}
}

return sb.ToString();
}




The next steps will be to test performance and find out what method is faster to check for IsNumber().

3 comments:

  1. Thanks for writing this.

    ReplyDelete
  2. thanks, from costa rica, IT's Paradise!!! Come visit us. We are pura vida!

    ReplyDelete
  3. Here is a one line version:

    Regex.Replace(key, @"\d", "");

    I found at:
    http://dotnetperls.com/remove-numbers

    ReplyDelete