VBScript - Count occurrences in a text string
30 Jul 2009I was scripting some Active Directory extracts today and I needed to check if a string of text contained two colons. I was checking if the detail on particular entries was to minutes or seconds; e.g. 13:25:33 vs. 13:25 . I couldn’t find a function to count occurrences within a string so I ended up writing my own….
The code below includes some examples of how to use it, but the
CountOccurrences()
function takes three parameters. the first is
the string to be searched through. the second is the string to search
for. The third is a Boolean that determines if the search should be
case sensitive. The function returns the count of occurrences.
Option Explicit
Const TEST_STRING = "This is just a random bit of text I typed in"
'Lower case 'i's = 4
'Upper case 'I's = 1
'Any case 'i's = 5
'Any case 'is's = 2
MsgBox "Count: " & CountOccurrences(TEST_STRING, "i", true), _
vbInformation + vbOKOnly, _
"Count of lower case 'i's"
MsgBox "Count: " & CountOccurrences(TEST_STRING, "I", true), _
vbInformation + vbOKOnly, _
"Count of upper case 'I's"
MsgBox "Count: " & CountOccurrences(TEST_STRING, "I", false), _
vbInformation + vbOKOnly, _
"Count of any case 'I's"
MsgBox "Count: " & CountOccurrences(TEST_STRING, "IS", false), _
vbInformation + vbOKOnly, _
"Count of any case 'IS's"
Function CountOccurrences(p_strStringToCheck, p_strSubString, p_boolCaseSensitive)
Dim arrstrTemp
Dim strBase, strToFind
If p_boolCaseSensitive Then
strBase = p_strStringToCheck
strToFind = p_strSubString
Else
strBase = LCase(p_strStringToCheck)
strToFind = LCase(p_strSubString)
End If
arrstrTemp = Split(strBase, strToFind)
CountOccurrences = UBound(arrstrTemp)
End Function
The function works by using VBScript’s split function to break the string into an array and then returns the upper bound which is equal in value to the number of times the string occurs.