Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrences of a character in a string

Tags:

vb6

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
like image 759
Gary Kindel Avatar asked Mar 15 '11 16:03

Gary Kindel


People also ask

How do you count the occurrences of a given character in a string in Python?

Python String count() The count() method returns the number of occurrences of a substring in the given string.

How do you count occurrences of a word in a string?

Approach: First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.


2 Answers

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

distinctChr = " "
count = Len(text) - Len(Replace(text, distinctChr , ""))
like image 197
Matt Avatar answered Sep 30 '22 11:09

Matt


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
like image 23
RS Conley Avatar answered Sep 30 '22 09:09

RS Conley