在一个字符串中计算特定字符出现的次数

73
什么是在字符串中计算特定字符出现次数的最简单方法?
也就是说,我需要编写一个名为countTheCharacters()的函数,以便进行计数。
str = "the little red hen"
count = countTheCharacters(str,"e") ' Count should equal 4
count = countTheCharacters(str,"t") ' Count should equal 3

最快的方法不是使用字符串。如果您真的对速度感兴趣,应该寻找其他东西。 - habakuk
1
@habakuk,除了“小红母鸡”之外,OP可以使用哪些非字符串值? - johny why
26个回答

0

使用:

Function fNbrStrInStr(strin As Variant, strToCount As String)
    fNbrStrInStr = UBound(Split(strin, strToCount)) - LBound(Split(strin, strToCount))
End Function

我使用strin作为变量来处理非常长的文本。拆分可以基于零或一,具体取决于用户设置,减去它可以确保正确的计数。

我没有包含一个测试来检查strcount是否比strin更长,以保持代码简洁。


0
我使用以下函数。它不是最节省内存的,但非常容易理解,支持多种比较方法,只有4行,速度快,在VBA中大部分情况下都能正常工作,可以找到任何搜索字符串(我经常搜索VbCrLf(s))。
唯一缺少的是从不同的“开始”开始搜索的能力。
    Function inStC(myInput As String, Search As String, Optional myCompareMethod As Long = CompareMethod.Text) As Long
        If InStr(1, myInput, Search, myCompareMethod) = 0 Then Return 0
        Return UBound(Split(myInput, Search,, myCompareMethod))
    End Function

我喜欢的一件事是它使用紧凑的例子。

str="the little red hen"
count=inStC(str,"e") 'count should equal 4
count=inStC(str,"t") 'count should equal 3

在这里,我想推荐我的inStB函数,它不仅可以返回字符串的计数,而且如果搜索字符串存在,它将简单地返回一个布尔值。我经常需要使用这个函数,这使得我的代码更加简洁。

Function inStB(myInput As String, Search As String, Optional Start As Long = 1, Optional myCompareMethod As Long = CompareMethod.Text) As Boolean
    If InStr(Start, myInput, Search, myCompareMethod) > 0 Then Return True
    Return False
End Function

0
    ' Trying to find the amount of "." in the text
    ' if txtName looks like "hi...hi" then intdots will = 3
    Dim test As String = txtName.Text
    Dim intdots As Integer = 0
    For i = 1 To test.Length
        Dim inta As Integer = 0 + 1
        Dim stra As String = test.Substring(inta)
        If stra = "." Then
            intdots = intdots + 1
        End If
    Next
    txttest.text = intdots

-3
Private Sub Data_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Data.KeyPress
    If Not IsNumeric(e.KeyChar) And Not e.KeyChar = ChrW(Keys.Back) And Not e.KeyChar = "." Then
        e.Handled = True
    Else
        If e.KeyChar = "." And Data.Text.ToCharArray().Count(Function(c) c = ".") > 0 Then
            e.Handled = True
        End If
    End If
End Sub

-3

使用:

Dim a
inputString = InputBox("Enter String", "Enter Value", "")

MyString = UCase(inputString)

MsgBox MyString

Dim stringLength

stringLength = Len(MyString)

Dim temp

output = ""

i = 1
Do
    temp = Mid(MyString, i, 1)

    MsgBox temp & i

    CharacterCount = len(MyString) - len(Replace(MyString, temp, ""))

    MyString = Replace(MyString, temp, "")

    output = output & temp & ": " & CharacterCount & vbNewline

Loop While MyString <> ""

MsgBox output

这是什么?它甚至无法编译,即使使用“显式关闭”和“选项严格关闭”也不行。 - Peter Mortensen
它是另一种基本形式,例如Visual Basic 6.0VBScript吗?这个问题是关于VB.NET的。 - Peter Mortensen

-9
这里是直接解决OP问题的代码:
        Dim str As String = "the little red hen"

        Dim total As Int32

        Dim Target As String = "e"
        Dim Temp As Int32
        Dim Temp2 As Int32 = -1
Line50:
        Temp = str.IndexOf(Target, Temp2 + 1)
        Temp2 = Temp
        If Temp <> -1 Then

            ' Means there is a target there
            total = total + 1
            GoTo Line50
        End If

        MessageBox.Show(CStr(total))

现在,这是一个解决OP问题的方便函数:

    Public Function CountOccurrence(ByVal YourStringToCountOccurrence As String, ByVal TargetSingleCharacterToCount As String) As Int32
        Dim total As Int32

        Dim Temp As Int32
        Dim Temp2 As Int32 = -1
Line50:
        Temp = YourStringToCountOccurrence.IndexOf(TargetSingleCharacterToCount, Temp2 + 1)
        Temp2 = Temp
        If Temp <> -1 Then

            ' Means there is a target there
            total = total + 1
            GoTo Line50
        Else
            Return total
        End If
    End Function

使用该函数的示例:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim str As String = "the little red hen"

    MessageBox.Show(CStr(CountOccurrence(str, "e")))
    ' It will return 4
End Sub

8
很抱歉,你的表述非常冗长,而且你还使用了GOTO语句!请参考这篇文章(http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html),它解释了为什么不应该使用GOTO语句。 - Basic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接