vb.net - 计算字符串中特定字符的出现次数

标签 vb.net string

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

也就是说,我需要编写一个函数,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/

相关文章:

sql - VB.Net 插入多条记录

c# - 在Linq查询中选择不重复

java - 在 Android 中的两个 Activity 之间传递字符串数组时出现 NullPointer

java - JTextArea 行到 ArrayList<String>

c - 修改基数转换

.net - 几个 Visual Studio 项目提示缺少临时文件,因此无法打开。错误代码&H80070003

c# - 以编程方式设置 IIS 6.0 的服务器绑定(bind)

c# - 使用 Process.Start 修复 CA2122

python - 在函数定义中正确使用 lambda

c++ - 索引到字符串时输出不正确