CSharp (C#) String Test

So, in an attempt to extract digits out of a string of variable length, which technique is better?

This was primarily a test of the Enumerable.Range() method, but then turned into a refactoring question.

This, of course assumes Dot Net 3.5 (LINQ) is available:

Code showing two methods and a test method

 

posted @ Friday, May 15, 2009 5:03 AM
Print

Comments on this entry:

# re: CSharp (C#) String Test

Left by Bill at 5/15/2009 11:38 PM
Gravatar
I think that is you are going with Linq, then this line is more readable, at least (did not do performance analysis, but it probably performs better as well):

public static string DigitsOnlyTest3(string rawData)
{
return new string(rawData.Where(c => char.IsDigit(c)).ToArray());
}

The reason is because your future reader will wonder why you are generating a range of characters begining with '0' (ohh or zero?), not reusing that enumeration (generate them each time through) even though this is a static set {0,1,2,3,4,5,6,7,8,9}. The contains method is Order-n (I think), so a bunch of 9's take longer than a bunch of zeros to verify, the number 10 in the code will throw readers off (Oh yea, the ascii codes zero through 9 are 10 things).

The above example, assuming the reader realizes that strings are IEnumerable<Char>, is easy to understand that we are picking out the "Digits" in the string.

I do not know what IsDigit actually does, but it could be better than code you/we write for various reasons.

[Please excuse typo's]

# re: CSharp (C#) String Test

Left by gordge at 8/3/2009 7:44 AM
Gravatar
bad bad worst for ever

Your comment:



(not displayed)

 
 
 
 
 

Live Comment Preview:

 
«July»
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789