In my last
post, I stated that I knew of only one way to find a count of all the substrings within a string without looping through the string. Well, a co-worker pointed out to me the other day that I had shown a non-looping way to count all the substrings within a string when I gave a class on Regular Expressions.
That is true. A very simple Regular expression:
new Regex(mySubString).Matches(myString).Count
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)
{
count++;
}
}