The number of occurrences of a character in a string

Look for the best way to do this in VB6. Generally, I would use this approach ...

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

I would use a modified basket view:

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. Performance O (N) - if Mid$- O (1).

Edit :

Based on your explanation, do the following:

   ' 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 a comparison, ascii should be faster than string comparison. I would have this profile just in case, but I'm sure.

+1
source

Not to say that this is the best way, but you are making code:

distinctChr = " "
count = Len(text) - Len(Replace(text, distinctChr , ""))
+14
source

split,

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

.

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

. 40 000 , , 17 Intel Core 2 2,4 .

:

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
+5

, .

If you want something very fast, but completely inconspicuous, adapt this horrible code that plunges into the base memory of a VB6 line to count the number of words. Courtesy of VBspeed .

0
source

All Articles