by Chris_Lucas (5 Submissions)
Category: String Manipulation
Compatability: Visual Basic 3.0
Difficulty: Advanced
Date Added: Wed 3rd February 2021
Rating: (4 Votes)
A small ultra-fast function used to count the number of words in a string.
Inputs
Text -the string in which to count words
Code Returns
The number of words counted is returned as the value of the function itself (as a long).
Side Effects
As this function makes use of CopyMemory it should be allowed to run until finished. Stopping the project in the IDE could result in VB crashing (as with ALL API calls).
API DeclarationsPrivate Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _
Destination As Any, _
Source As Any, _
ByVal Length As Long)
' © Christopher Lucas 2001
' You may freely use and distribute this code
' in all your applications. Recognition is
' appreciated though.
Public Function WordCount(Text As String) As Long
Dim dest() As Byte
Dim i As Long
If LenB(Text) Then
' Move the string's byte array into dest()
ReDim dest(LenB(Text))
CopyMemory dest(0), ByVal StrPtr(Text), LenB(Text) - 1
' Now loop through the array and count the words
For i = 0 To UBound(dest) Step 2
If dest(i) > 32 Then
Do Until dest(i) < 33
i = i + 2
Loop
WordCount = WordCount + 1
End If
Next i
Erase dest
Else
WordCount = 0
End If
End Function