Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB4,VB5,VB6
Expertise: Intermediate
Sep 22, 2001

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 
Everything is easier if you use the capability to move a string into a Byte array. Here is a complete routine:

' count spaces
Function 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
    CountSpaces = count
End Function 
This approach can be up to three times faster than the traditional one.
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.