29
Gathering Information about Strings
55
Counting the Number of Tokens in a Delimited String
The dhCountTokens function, shown in Listing 1.10, is a general-purpose func-
tion that allows you to find out how many “chunks” of text there are in a string,
given text delimiters that you supply. The function interprets any one of the char-
acters in your list of delimiters as a token separator, so
Debug.Print dhCountTokens("This is a test", " ")
returns 4, as does
Debug.Print dhCountTokens("This:is!a test", ": !")
Because every delimiter character must delimit a token, the following example
returns 10:
Debug.Print dhCountTokens("This:!:is:!:a:!:test", ": !")
You’ll have to look carefully to see them, but the individual tokens are
This, "", "", is, "", "", a, "", "", test
Counting Vowels Revisited
You could use the dhCountIn function to count vowels, as shown in the previous example. You
might also take advantage of the dhTranslate and Split functions to do the same job. That
is, you can have dhTranslate replace all vowels with a single vowel, and then use the Split
function to split the text, based on that single vowel. The size of the array returned from
Split tells you how many vowels you have. For example, you might write the code this way
(see the next section for more information on using dhTranslate in this manner):
Public Function CountVowels(ByVal strIn As String) As Long
' An alternative way to calculate vowels in a piece of text.
Dim astrItems() As String
strIn = dhTranslate(strIn, "AEIOU", "A", vbTextCompare)
astrItems = Split(strIn, "A")
CountVowels = UBound(astrItems) - LBound(astrItems)
End Function