【问题标题】:Count specific character occurrences in a string计算字符串中特定字符的出现次数
【发布时间】:2011-07-08 19:27:42
【问题描述】:

计算字符串中特定字符出现次数的最简单方法是什么?

也就是说,我需要写一个函数countTheCharacters(),这样

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

【问题讨论】:

  • 最快的方法是不使用字符串。如果你真的对速度感兴趣,你应该寻找其他东西。
  • @habakuk,OP 可以使用什么非字符串值来代替“小红母鸡”?
  • @johnywhy 为什么要使用 StringBuilder。见msdn.microsoft.com/de-de/library/…

标签: vb.net string


【解决方案1】:

最直接的就是简单地遍历字符串中的字符:

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Dim cnt As Integer = 0
  For Each c As Char In value
    If c = ch Then 
      cnt += 1
    End If
  Next
  Return cnt
End Function

用法:

count = CountCharacter(str, "e"C)

另一种几乎同样有效且代码更短的方法是使用 LINQ 扩展方法:

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Return value.Count(Function(c As Char) c = ch)
End Function

【讨论】:

  • 我来这里是为了寻找最快的方法,不一定是最优雅的方法。这很快,但可以通过使用For i as Integer = 0 to value.Length - 1 而不是 For Each 循环来提高 10% 左右。
  • 'Count' is not a member of 'String'.
  • @Panzercrisis:Count 方法是IEnumerable<T> 的扩展方法,String 实现了IEnumerable<char>。如果您收到类似的编译器错误,则说明您缺少页面顶部的 using System.Linq; 引用。
  • 此逻辑也可用于 VBA:Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer Dim cnt As Integer For Each c In value If c = ch Then cnt = cnt + 1 End If Next CountCharacter = cnt End Function
  • 答案和 cmets 中的代码不会粘贴到 VBA 并在第一次尝试时工作。这是一些 VBA 代码,以防有人在寻找它: Private Function CountCharacter(WhatToSearch As String, SearchForThis As String) As Long Dim NumberOfHits As Long Dim i As Long For i = 1 To Len(WhatToSearch) If Mid(WhatToSearch, i , 1) = SearchForThis Then NumberOfHits = NumberOfHits + 1 End If Next CountCharacter = NumberOfHits End Function
【解决方案2】:

这是最简单的方法:

text = "the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3

【讨论】:

  • 如果开始字母或/和结束字母是要计数的,这并不总是正确的数字
  • @Remonn 它总是给我正确的数字。它不计算开始/结束字母的唯一方法是,如果您将 SplitStringOptions.RemoveEmptyEntries 作为第二个参数传递给 Split()
  • 这很简单,但是它创建了一堆甚至没有用于任何东西的字符串。
  • @Guffa,由于拆分未应用于变量,分配给拆分的任何内存不会立即释放,还是我们退出函数后立即释放?取决于特定的语言,我想......
  • @johnywhy:内存不会立即释放,字符串会保留在内存中,直到垃圾收集器可以收集它们。短期对象很常见,垃圾收集器经过优化可以有效地处理它们,但它们仍然会增加分配吞吐量并为垃圾收集器带来更多工作。这是由框架处理的,因此对于所有 .NET 语言都是一样的。
【解决方案3】:

你可以试试这个

Dim occurCount As Integer = Len(testStr) - Len(testStr.Replace(testCharStr, ""))

【讨论】:

  • 将你的答案除以Len(testCharStr)Ceil 它也适用于字符串的出现。
  • 这个方法的好处是,它使用了非常基本的效果。没有 LINQ、RegEx 或其他额外的库。可以很容易地用各种语言复制。
【解决方案4】:

这是一个简单的版本。

text.count(function(x) x = "a")

上面会给你字符串中a的数量。如果你想忽略大小写:

text.count(function(x) Ucase(x) = "A")

或者如果你只是想数字母:

text.count(function(x) Char.IsLetter(x) = True)

试一试!

【讨论】:

  • 这在我看来不像 vb.net 解决方案。
  • 这是一个非常 VB.NET 的解决方案!
  • 失败。我的 VS 2017 没有字符串的 .count。
  • @DougNull 我已经摆脱了 VB 和 .Net 开发。当我回到家时,我可能会搞砸这个。您是否尝试过导入 Linq?我想知道这是否会有所作为。我可以向您保证,这在过去对我和其他人都有效,但您会注意到该解决方案是在 2014 年发布的。我不知道从那时起是否发生了破坏此问题的更改。如果他们有,我会很失望。可能只是 lambda 表达式的实现方式发生了变化?
【解决方案5】:

或者(在 VB.NET 中):

Function InstanceCount(ByVal StringToSearch As String,
                       ByVal StringToFind As String) As Long
    If Len(StringToFind) Then
        InstanceCount = UBound(Split(StringToSearch, StringToFind))
    End If
End Function

【讨论】:

    【解决方案6】:

    Ujjwal Manandhar 的代码到 VB.NET 的转换如下...

    Dim a As String = "this is test"
    Dim pattern As String = "t"
    Dim ex As New System.Text.RegularExpressions.Regex(pattern)
    Dim m As System.Text.RegularExpressions.MatchCollection
    m = ex.Matches(a)
    MsgBox(m.Count.ToString())
    

    【讨论】:

    • 谢谢,我选择了这个版本。似乎也非常快。我实际上是在文本字符串中搜索 CR 和/或 LF 以及频率,因此我可以调整 Gridview 中文本框的大小和高度以支持输出。
    【解决方案7】:

    谢谢,@guffa。在 .NET 中,在一行甚至更长的语句中执行此操作的能力非常方便。这个 VB.NET 示例计算 LineFeed 字符的数量:

    Dim j As Integer = MyString.Count(Function(c As Char) c = vbLf)
    

    j 返回 MyString 中 LineFeed 的数量。

    【讨论】:

      【解决方案8】:

      我认为这是最简单的:

      Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
        Return len(value) - len(replace(value, ch, ""))
      End Function
      

      【讨论】:

        【解决方案9】:
        Public Class VOWELS
        
            Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
                Dim str1, s, c As String
                Dim i, l As Integer
                str1 = TextBox1.Text
                l = Len(str1)
                c = 0
                i = 0
                Dim intloopIndex As Integer
                For intloopIndex = 1 To l
                    s = Mid(str1, intloopIndex, 1)
                    If (s = "A" Or s = "a" Or s = "E" Or s = "e" Or s = "I" Or s = "i" Or s = "O" Or s = "o" Or s = "U" Or s = "u") Then
                        c = c + 1
                    End If
                Next
                MsgBox("No of Vowels: " + c.ToString)
            End Sub
        End Class
        

        【讨论】:

          【解决方案10】:

          当我找到这个解决方案时,我正在寻找一些稍微不同的东西,因为我想要计算的字符串比一个字符长,所以我想出了这个解决方案:

              Public Shared Function StrCounter(str As String, CountStr As String) As Integer
                  Dim Ctr As Integer = 0
                  Dim Ptr As Integer = 1
                  While InStr(Ptr, str, CountStr) > 0
                      Ptr = InStr(Ptr, str, CountStr) + Len(CountStr)
                      Ctr += 1
                  End While
                  Return Ctr
              End Function
          

          【讨论】:

            【解决方案11】:

            使用正则表达式...

            Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
              Return (New System.Text.RegularExpressions.Regex(ch)).Matches(value).Count
            End Function
            

            【讨论】:

              【解决方案12】:
              Public Function CountOccurrences(ByVal StToSerach As String, ByVal StToLookFor As String) As Int32
              
                  Dim iPos = -1
                  Dim iFound = 0
                  Do
                      iPos = StToSerach.IndexOf(StToLookFor, iPos + 1)
                      If iPos <> -1 Then
                          iFound += 1
                      End If<br/>
                  Loop Until iPos = -1
                  Return iFound
              End Function
              

              代码用法:

              Dim iCountTimes As Integer = CountOccurrences("Can I call you now?", "a")
              

              您也可以将其作为扩展:

              <Extension()> _
              Public Function CountOccurrences(ByVal StToSerach As String, ByVal StToLookFor As String) As Int32
                  Dim iPos = -1
                  Dim iFound = 0
                  Do
                      iPos = StToSerach.IndexOf(StToLookFor, iPos + 1)
                      If iPos <> -1 Then
                          iFound += 1
                      End If
                  Loop Until iPos = -1
                  Return iFound
              End Function
              

              代码用法:

              Dim iCountTimes2 As Integer = "Can I call you now?".CountOccurrences("a")
              

              【讨论】:

              • 在 Stack Overflow 上,您可以使用编辑器中的 {} 按钮格式化代码。这次我为你做了这个修改。
              【解决方案13】:

              我建议你这样做:

              String.Replace("e", "").Count
              String.Replace("t", "").Count
              

              您也可以分别使用.Split("e").Count - 1.Split("t").Count - 1,但如果您在String 的开头有e 或a,则会给出错误的值。

              【讨论】:

              • 这是 vb.net 吗?我没有安装 Visual Studio,但 dotnetfiddle.net 和 ideone.com 都报告“'count' 不是 'String' 的成员。”
              【解决方案14】:
              eCount = str.Length - Replace(str, "e", "").Length
              tCount = str.Length - Replace(str, "t", "").Length
              

              【讨论】:

                【解决方案15】:

                另一种可能性是使用拆分:

                Dim tmp() As String
                tmp = Split(Expression, Delimiter)
                Dim count As Integer = tmp.Length - 1
                

                【讨论】:

                  【解决方案16】:

                  我用的是LINQ,解决方法很简单:

                  C# 中的代码:

                  count = yourString.ToCharArray().Count(c => c == 'e');
                  

                  函数中的代码:

                  public static int countTheCharacters(string str, char charToCount){
                     return str.ToCharArray().Count(c => c == charToCount);
                  }
                  

                  调用函数:

                  count = countTheCharacters(yourString, 'e');
                  

                  【讨论】:

                  • 我在下面发布了一些类似 vb.net 的内容。
                  【解决方案17】:

                  这么简单的东西有多大的代码:

                  在 C# 中,创建扩展方法并使用 LINQ。

                  public static int CountOccurences(this string s, char c)
                  {
                      return s.Count(t => t == c);
                  }
                  

                  用法:

                  int count = "toto is the best".CountOccurences('t');
                  

                  结果:4。

                  【讨论】:

                    【解决方案18】:

                    我找到了最佳答案 :P :

                    String.ToString.Count - String.ToString.Replace("e", "").Count
                    String.ToString.Count - String.ToString.Replace("t", "").Count
                    

                    【讨论】:

                      【解决方案19】:

                      var charCount = "string with periods...".Count(x =&gt; '.' == x);

                      【讨论】:

                        【解决方案20】:

                        我使用以下功能。它不是最节省内存的,但很容易理解,支持多种比较方法,只有 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
                        

                        【讨论】:

                          【解决方案21】:

                          另一种可能是使用正则表达式:

                          string a = "this is test";
                          string pattern = "t";
                          System.Text.RegularExpressions.Regex ex = new System.Text.RegularExpressions.Regex(pattern);
                          System.Text.RegularExpressions.MatchCollection m = ex.Matches(a);
                          MessageBox.Show(m.Count.ToString());
                          

                          请将其转换为 VB.NET。

                          【讨论】:

                            【解决方案22】:

                            用途:

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

                            我使用strin 作为变体来处理很长的文本。根据用户设置,分割可以是从零开始,也可以是从低端开始,减去它可以确保正确的计数。

                            为了保持代码简洁,我没有对 strcount 长于 strin 进行测试。

                            【讨论】:

                              【解决方案23】:
                                  ' 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
                              

                              【讨论】:

                                【解决方案24】:
                                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
                                

                                【讨论】:

                                  【解决方案25】:

                                  用途:

                                  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
                                  

                                  【讨论】:

                                  • 这是什么?它甚至不能编译,即使是 Explicit OffOption Strict Off
                                  • 是其他形式的 Basic,例如 Visual Basic 6.0VBScript?问题是关于VB.NET
                                  【解决方案26】:

                                  这是解决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
                                  

                                  【讨论】:

                                  猜你喜欢
                                  • 1970-01-01
                                  • 2022-10-05
                                  • 1970-01-01
                                  • 2017-09-24
                                  • 1970-01-01
                                  • 2019-12-10
                                  • 1970-01-01
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多