Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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.

 

 

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