String
occurrence countSuppose a string
in your VB.NET program contains several duplicated words within it. With a method that counts string
occurrences, we can determine the duplicate count.
With a While True loop, we can continue looping over the string
contents until all instances have been found. We can invoke IndexOf
to find each next occurrence.
Here we introduce a string
that contains 2 occurrences of the word "cat" and 1 occurrence of "frog." We then call CountStringOccurrences
to count these occurrences.
CountStringOccurrences
, we have a couple local variables to keep track of our count, and the position in the loop.While
-True loop, and in each iteration, we find the next instance of the pattern with IndexOf
.IndexOf
returns -1 if the string
is not located. This will cause us to exit the enclosing While loop.Module Module1 Sub Main() Dim value as String = "cat, frog, cat" ' There should be 2, 1, and 0 instances of these strings. Console.WriteLine("cat = {0}", CountStringOccurrences(value, "cat")) Console.WriteLine("frog = {0}", CountStringOccurrences(value, "frog")) Console.WriteLine("DOG = {0}", CountStringOccurrences(value, "DOG")) End Sub Function CountStringOccurrences(value as String, pattern as String) As Integer ' Count instances of pattern in value. Dim count as Integer = 0 Dim i as Integer = 0 While True ' Get next position of pattern. i = value.IndexOf(pattern, i) ' If not found, exit the loop. If i = -1 Exit While End If ' Record instance of the pattern, and skip past its characters. i += pattern.Length count += 1 End While Return count End Function End Modulecat = 2 frog = 1 DOG = 0
If you have a common need to count strings within another string
, you could write out the While loop in each place. But encapsulating this logic in a Function is easier to reason about.
The IndexOf
method in VB.NET is often called within loops, and we can use it to count matching parts of a string
. This forms the core part of our method.