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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.



Thanks for your registration, follow us on our social networks to keep up-to-date