Count distinct characters in a string

When you need to count how many occurrences of a given character are in a string, you might be tempted to go along the “traditional” Visual Basic way:

    ' count spaces    For i = 1 To Len(text)        If Mid$(text, i, 1) = " " Then count = count + 1     Next

Everything is easier if you use the capability to move a string into a Byte array. Here is a complete routine:

' count spacesFunction CountSpaces(ByVal sText As String) As Long    Dim bArr() As Byte    Dim i As Long    Dim count As Long        bArr() = sText    For i = 0 To UBound(bArr) Step 2        ' if this char is a space, increase the counter        If bArr(i) = 32 Then count = count + 1    Next    CountSpaces = countEnd Function 

This approach can be up to three times faster than the traditional one.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: