Home
VB.NET
String Occurrence Count
Updated Nov 8, 2023
Dot Net Perls
String occurrence count. Suppose 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.
String IndexOf
Example. 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.
Important In CountStringOccurrences, we have a couple local variables to keep track of our count, and the position in the loop.
Next We enter a While-True loop, and in each iteration, we find the next instance of the pattern with IndexOf.
Note IndexOf returns -1 if the string is not located. This will cause us to exit the enclosing While loop.
Finally In each iteration, we increment the count (which is the result value) and also skip past to the next character position.
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 Module
cat = 2 frog = 1 DOG = 0
Some uses. 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.
Function
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 8, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen