计算字符串中某个字符的出现次数 [英] Count occurrences of a character in a string

查看:39
本文介绍了计算字符串中某个字符的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在寻找在 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

推荐答案

我会使用修改后的桶排序:

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

...您的结果在 count 中.性能是 O(N) - 如果 Mid$ 是 O(1).

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

编辑:

根据您的说明,执行以下操作:

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

ascii 比较必须比字符串比较快.以防万一,我会对其进行分析,但我很确定.

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

这篇关于计算字符串中某个字符的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆