我有一个字符串中的分隔符,我必须验证。如何计算该char的出现次数。现在我有下一个功能。
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
任何看起来更好的替代解决方案?
答案 0 :(得分:6)
或者您可以使用LINQ ..
Private Function CountChars(ByVal value As String) As Integer
Return value.ToCharArray().Count(Function(c) c = "$"c)
End Function
正如Meta-Knight指出的那样,它可以缩短为:
value.Count(Function(c) c = "$"c)
答案 1 :(得分:2)
我能想到的最简单,最通用的方式:
Private Shared Function CountChars(ByVal value As String, Byval delim as String) As Integer
Return Len(value) - Len(Replace(value, delim, ""))
End Function
答案 2 :(得分:1)
您可以通过多种方式检查出现次数。请参阅以下代码,如果您发现它更好,则可以使用它。
Dim Occurrences As Integer
Dim Start As Integer
Dim Found As Integer
Do
Start = Found + 1
Found = InStr(Start, "ENTERTAINMENT", "E")
If Found = 0 Then Exit Do
Occurrences += 1
Loop