计算字符串中特定字符的出现次数 [英] Count specific character occurrences in a string
本文介绍了计算字符串中特定字符的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
计算字符串中特定字符出现次数的最简单方法是什么?
What is the simplest way to count the number of occurrences of a specific character in a string?
也就是说,我需要写一个函数,countTheCharacters(),以便
That is, I need to write a function, countTheCharacters(), so that
str = "the little red hen"
count = countTheCharacters(str,"e") ' Count should equal 4
count = countTheCharacters(str,"t") ' Count should equal 3
推荐答案
最直接的就是简单地循环遍历字符串中的字符:
The most straightforward is to simply loop through the characters in the string:
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 扩展方法:
Another approach that is almost as effective and gives shorter code is to use LINQ extension methods:
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Return value.Count(Function(c As Char) c = ch)
End Function
这篇关于计算字符串中特定字符的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文