I want to count how many /
s I could find in a string. There are several ways to do it, but I couldn't decide on what the best (or easiest) is.
At the moment I'm going with something like:
string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;
Or for strings where length > 1:
string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;
Best Answer
If you're using .NET 3.5 you can do this in a one-liner with LINQ:
If you don't want to use LINQ you can do it with:
You might be surprised to learn that your original technique seems to be about 30% faster than either of these! I've just done a quick benchmark with "/once/upon/a/time/" and the results are as follows:
(The times are for 50,000,000 iterations so you're unlikely to notice much difference in the real world.)