计数出现在字符串中的字符的数目? [英] Count the number of occurrences of a char in a string?

查看:194
本文介绍了计数出现在字符串中的字符的数目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/5193893/count-specific-character-occurances-in-string">Count特定字符occurances字符串

我在字符串中的分隔符,我有能力验证。我怎么能指望出现了焦炭。现在我有一个下一个功能。

I have a delimeter in string that i have to validate. How can I count occurrences of that char. For now i have a next function.

Private Shared Function CountChars(ByVal value As String) As Integer
    Dim count = 0
    For Each c As Char In value
        If c = "$"c Then
            count += 1
        End If
    Next
    Return count
End Function

任何替代方案,看起来好?

Any alternative solution that looks better?

推荐答案

或者你可以使用LINQ。

Or you could use LINQ..

Private Function CountChars(ByVal value As String) As Integer

    Return value.ToCharArray().Count(Function(c) c = "$"c)

End Function

作为元奈特指出,它可以缩短为:

As Meta-Knight has pointed out it can be shortened to:

value.Count(Function(c) c = "$"c)

这篇关于计数出现在字符串中的字符的数目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆