It's an interesting .NET performance question. Just to see how fast each
technique was I wrote a quick test to compare three methods:
Method 1 uses a foreach loop to retrieve each character in the string.
Method 2 uses ToCharArray() to get all the characters in the string, then
uses a for loop (not foreach) to go through each character in the array.
Method 3 uses a Regex and gets the Regex.Matches.Count property.
With a test string that contains 83 characters (arbitrary) it turns out that
method 2 is about five or six times faster than method 1, and about a
hundred times faster than method 3.
With a test string that contains 1000 characters method 2 gets even better,
outperforming method 1 by 7.5 to 1 and method 3 by 150 to 1.
Modifying method 2 to use foreach instead of for didn't measureably change
the performance.
Here's method 2 code:
int CountChar(string s, char ch)
{
int count = 0;
char[] a = s.ToCharArray();
foreach (char c in a)
if (c == ch)
count++;
return count;
}
"Jon Skeet" <sk***@pobox.com> wrote in message
news:MP************************@news.microsoft.com ...
Ralph Gerbig <ik********@web.de> wrote: parse the string with a regex put the matches in a MatchCollection and
take the count Property of the MatchCollection
That sounds like an awful lot of work though for something which is
pretty simple. I personally think that regular expressions are rather
overused. They're incredibly powerful, but sometimes a nail is just a
nail, and doesn't need a powertool, just a hammer :)
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too