Counting the Occurrences of a Substring

Counting the Occurrences of a Substring

VB6 has introduced the Replace function, which replaces all occurrences of a substring with another substring. Although this function is useful in itself, you can also use it in unorthodox ways. For instance, you can use it to count how many times a substring appears inside another string:

 Function InstrCount(Source As String, Search As String) _	As Long	InstrCount = Len(Source) - Len(Replace(Source, Search, _		Mid$(Search, 2)))End Function 

This code uses the Replace function to replace the searched substring with another substring one character shorter. This means the difference between the original string and the string returned by the Replace function is equal to the number of occurrences of the substring.


Share the Post: