How would you count occurrences of a string (actually a char) within a string?
If you want to be able to search for whole strings, and not just characters:
src.Select((c, i) => src.Substring(i))
.Count(sub => sub.StartsWith(target))
Read as "for each character in the string, take the rest of the string starting from that character as a substring; count it if it starts with the target string."
int count = new Regex(Regex.Escape(needle)).Matches(haystack).Count;
string source = "/once/upon/a/time/";
int count = 0;
foreach (char c in source)
if (c == '/') count++;
Has to be faster than the source.Replace()
by itself.
If you're using .NET 3.5 you can do this in a one-liner with LINQ:
int count = source.Count(f => f == '/');
If you don't want to use LINQ you can do it with:
int count = source.Split('/').Length - 1;
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:
Your original = 12s
source.Count = 19s
source.Split = 17s
foreach (from bobwienholt's answer) = 10s
(The times are for 50,000,000 iterations so you're unlikely to notice much difference in the real world.)