tisdag 18 juni 2013

Count occurences of a substring within a string

If you want to figure out how many times a string appears within another string there are numerous ways of doing this. I found a nice way I like that i will share here.

Note that this will not work as intended if the substrings "overlap" each other.
So this example would need another solution: How many times does "bob" appear in "bobobob"?


This particular way of doing it works looks like this:

int count = ( string.Length - string.Replace(substring, string.empty).Length ) / substring.Length;

Basically we count how many times we can remove the substring from the string...


This solution came from here:
http://oldschooldotnet.blogspot.se/2008/12/c-counting-number-of-occurrences-of.html