计数出现在字符串中的字符的数目?出现在、字符串、数目、字符

2023-09-06 04:55:40 作者:差了点撕心裂肺∞

可能重复:   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)