计算字符串中特定字符出现次数的最简单方法是什么?
也就是说,我需要编写一个函数,countTheCharacters(),这样
str = "the little red hen"
count = countTheCharacters(str,"e") ' Count should equal 4
count = countTheCharacters(str,"t") ' Count should equal 3
最佳答案
最直接的方法是简单地循环字符串中的字符:
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
关于vb.net - 计算字符串中特定字符的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5193893/