Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Beginner
May 4, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date