I thought I'd give you something to work with until I get home. Try creating two textboxes, one for the input string to search and one for the pattern. Create a third textbox to show the number of matches found. Now try:
Code:
privatevoid btnSearch_Click(object sender, EventArgs e)
{
int matchCounter = 0;
int i;
int inputLength;
int patternLength;
string buffer = txtInputString.Text.ToLower(); // Make lower case
string target = txtTargetPattern.Text.ToLower();
inputLength = buffer.Length; // Get string lengths
patternLength = target.Length;
i = 0;
while (i < inputLength)
{
i = buffer.IndexOf(target, i);
if (i == -1) // We're done...
break;
matchCounter++; //...up the counter...
i += patternLength; //...and go to the end of the pattern
} // End while (i...
txtCount.Text = matchCounter.ToString();
}
First we convert both strings to lower case. You could add code to preserve case based on the state of a checkbox indicating the user wants the case preserved. I'll leave that to you (as well as error checking). Next, we get the lengths of the two strings, using the variable
i and
patterLength to control the
while loop. The method
IndexOf() returns an index telling where a match on the pattern is found. If no (further) match is found, the index returned is -1. Note that we use that to break out of the loop. If we do find a match, we record the match in
matchCounter and then advance past the match to look for additional matches.
I think if you single-step through the code, you'll see how it works.