devxlogo

Count distinct characters in a string

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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist