String Function – CountWords

This short routine shows how to code a routine to return the number of words in a string (including strings containing CR/LF codes).

'
'Description :
'
'"Countwords" function can be used to determine number of
'words in a multiline string. The function breaks the source string
'into lines and passes each line to the function "countwordsinline"
'to get number of words in each line.
' 
' 
public Function countwordsinline(byval sourceline as string) _
       as Long
    Dim nextspaceindex as Long
    sourceline = sourceline & " "
'Every word has space at its end
    nextspaceindex = InStr(sourceline, " ")
    While nextspaceindex <> 0
        If nextspaceindex <> 1 then countwordsinline = _
           countwordsinline + 1
        sourceline = mid$(sourceline, nextspaceindex + 1)
        nextspaceindex = InStr(sourceline, " ")
    Wend
End Function
'
public Function countwords(byval source as string) as Long
    Dim endindex as Long
    source = source & Chr$(13)
    endindex = InStr(source, Chr$(13))
    While (endindex <> 0)
        countwords = countwords + countwordsinline(mid$(source, _
                                                   1, endindex - 1))
        source = mid$(source, endindex + 2)
'VB vbCrLf contains 2 Characters
        endindex = InStr(source, Chr$(13))
    Wend
End Function
'

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read