by VB-Kung-Fu (19 Submissions)
Category: String Manipulation
Compatability: Visual Basic 5.0
Difficulty: Unknown Difficulty
Originally Published: Thu 9th October 2003
Date Added: Mon 8th February 2021
Rating: (1 Votes)
Counts the number of words in a string.
'this function finds the number of spaces in a string and from that
'determines how many words there are.
Dim SpaceAlreadyFound As Boolean, NumOfSpaces As Long, n As Long
Dim Character As String
'return zero if the string is empty.The trim ensures
'that a string of spaces is counted as invalid
If Trim(StringForWordCount) = "" Then Exit Function
'remove leading and trailing spaces
StringForWordCount = Trim(StringForWordCount)
'count the words
For n = 1 To Len(StringForWordCount) - 1
'go through each character
Character = Mid(StringForWordCount, n, 1)
'check if selected character is a space
If Character = Chr(32) Then
'check if a space has been found already
If SpaceAlreadyFound Then
'dont increment space count
Else
NumOfSpaces = NumOfSpaces + 1
SpaceAlreadyFound = True
End If
Else
'reset this because another character
'has been found
SpaceAlreadyFound = False
End If
Next n
'always add 1, since the number of words
'in a string is equivalent to the number
'of spaces + 1
WordCount = NumOfSpaces + 1
End Function