String Occurrence Count
This page was last reviewed on 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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 8, 2023 (new).
© 2007-2024 Sam Allen.