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

前端之家收集整理的这篇文章主要介绍了vb.net – 计算字符串中特定字符的出现次数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
计算字符串中特定字符出现次数的最简单方法是什么?

即我需要写一个函数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
  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
原文链接:https://www.f2er.com/vb/256432.html

猜你在找的VB相关文章