Search Tools Links Login

Lightning Fast Word Counting


A small ultra-fast function used to count the number of words in a string.

Original Author: Chris Lucas

Inputs

Text -the string in which to count words

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 Declarations

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _
Destination As Any, _
Source As Any, _
ByVal Length As Long)

Code

' 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

About this post

Posted: 2002-06-01
By: ArchiveBot
Viewed: 82 times

Categories

Visual Basic 6

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.