Gary Kindel
Gary Kindel

Reputation: 17699

Count occurrences of a character in a string

Looking for the best way to do this in VB6. Typically, I would use this approach...

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

Upvotes: 9

Views: 33706

Answers (4)

RS Conley
RS Conley

Reputation: 7196

Use the split command like this

Dim TempS As String
TempS = " This is a split  test "
Dim V As Variant
V = Split(TempS, " ")
Cls
Print UBound(V) '7
V = Split(TempS, "i")
Print UBound(V) '3
V = Split(TempS, "e")
Print UBound(V) '1

You can combine it to a single line.

Print UBound(Split(TempS, "i"))

I did some crude timing on it. On a 40,000 character string with all spaces it seems to clock in at 17 milliseconds on a 2.4 GHz Intel Core 2 processor.

A function could look like this

Function CountChar(ByVal Text As String, ByVal Char As String) As Long
    Dim V As Variant
    V = Split(Text, Char)
    CountChar = UBound(V)
End Function

Upvotes: 6

MarkJ
MarkJ

Reputation: 30398

It's not clear what you mean by the best way to do this.

If you want something very fast, but totally unmaintainable, adapt this horrible code that delves into the underlying memory of a VB6 string to count the number of words. Courtesy of VBspeed.

Upvotes: 0

Scott Whitlock
Scott Whitlock

Reputation: 13839

I would use a modified bucket sort:

Dim i as Integer
Dim index As Integer
Dim count as Integer
Dim FoundByAscii(0 To 255) As Boolean
For i = 1 To Len(text)
    index = Asc(Mid$(text, i, 1))
    FoundByAscii(index) = True
Next i
count = 0
For i = 0 To 255
    If FoundByAscii(i) Then
        count = count + 1
    End If
Next i

...and your result is in count. The performance is O(N) - if Mid$ is O(1).

Edit:

Based on your clarification, do this:

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

As ascii compares have to be faster that string comparison. I'd profile it just in case, but I'm pretty sure.

Upvotes: 1

Matt
Matt

Reputation: 14531

Not saying it's the best way, but you code do:

distinctChr = " "
count = Len(text) - Len(Replace(text, distinctChr , ""))

Upvotes: 24

Related Questions