计算字符串中特定字符出现次数的最简单方法是什么?
也就是说,我需要编写一个函数countTheCharacters(),这样
str = "the little red hen"
count = countTheCharacters(str,"e") ' Count should equal 4
count = countTheCharacters(str,"t") ' Count should equal 3
Run Code Online (Sandbox Code Playgroud)
Guf*_*ffa 66
最直接的是简单地遍历字符串中的字符:
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
Run Code Online (Sandbox Code Playgroud)
用法:
count = CountCharacter(str, "e"C)
Run Code Online (Sandbox Code Playgroud)
另一种几乎同样有效并且代码更短的方法是使用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
Run Code Online (Sandbox Code Playgroud)
Coy*_*ero 60
这是一种简单的方法:
text = "the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3
Run Code Online (Sandbox Code Playgroud)
小智 31
你可以试试这个
Dim occurCount As Integer = Len(testStr) - Len(testStr.Replace(testCharStr, ""))
Run Code Online (Sandbox Code Playgroud)
Mat*_*ttB 16
这是一个简单的版本.
text.count(function(x) x = "a")
Run Code Online (Sandbox Code Playgroud)
上面的内容将为您提供字符串中的数字.如果你想忽略大小写:
text.count(function(x) Ucase(x) = "A")
Run Code Online (Sandbox Code Playgroud)
或者,如果你只是想数字:
text.count(function(x) Char.IsLetter(x) = True)
Run Code Online (Sandbox Code Playgroud)
试一试!
或(在 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
Run Code Online (Sandbox Code Playgroud)
小智 5
将 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())
Run Code Online (Sandbox Code Playgroud)
谢谢,@guffa。能够在一行中完成,甚至在 .NET 中的更长语句中完成,这非常方便。这个 VB.NET 示例计算 LineFeed 字符的数量:
Dim j As Integer = MyString.Count(Function(c As Char) c = vbLf)
Run Code Online (Sandbox Code Playgroud)
j 返回 MyString 中 LineFeed 的数量。