That is true. A very simple Regular expression:
But, that simple line of code is not the reason for this post. I've found an even deeper issue, and it all comes down to how you define the problem (doesn't it always).
Lets say that my string is "BOBOBOB"
How many instances of the substring "BOB" is in "BOBOBOB"? 2 or 3?
My way in the previous post and the regular expression both agree, the number is 2.
But, say you are writing a game and you are using a string to store previous moves. Each move can have only two choices: a 0 or a 1. So after a number of moves, the storage string could look like this "0111110010100111110110111101".
Now, how many times did the player choose to play a 1 after playing a 1 the prior two moves, i.e. a "111"? If you did a substring search, you would get a 3. But if you count the number of times "111" appear including overlap, the number is much higher: 8.
So, an AI routine that was based on prior moves would need to find all combinations of "111" even if one set is partially contained within another.
So, here is my LOOP that counts the number of substrings within a string, even if the substring is partially contained within another substring.
for (var i = 0; i <= myString.Length - mySubString.Length; i++)
if (myString.Substring(i, mySubString.Length) == mySubString)