Alex Rivera | Logout

Count occurrences of a character in a string

Asked 2011-03-15T16:24:15.057
10

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
vb6
Edit
Report

1 Answer

6

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
answered 2011-03-15T18:11:20.937

Your Answer