2012-03-30 63 views
2

可能重複:
Count specific character occurances in string計算字符串中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 

任何替代解決方案看起來更好?

+1

http://stackoverflow.com/questions/5193893/count-specific-字符發生在字符串中有你的答案 – Marco 2012-03-30 07:44:44

+0

你的代碼是好的:)也許通過指定char作爲參數來通用。 – Bas 2012-03-30 07:48:39

回答

6

或者你可以使用LINQ ..

Private Function CountChars(ByVal value As String) As Integer 

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

End Function 

爲元奈特指出它可以縮短爲:

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

不錯的答案,但你可以刪除不需要的'.ToCharArray()'! – 2012-03-30 13:07:46

+1

我認爲CountChars函數甚至不需要,因爲代碼太短。你可以直接調用Count方法。 – 2012-03-30 13:11:44

+0

我更喜歡......'Value.Split(「$」c).Length-1' – 2013-08-19 15:38:42

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 
2

最簡單和最通用的方式,我能想到的:

Private Shared Function CountChars(ByVal value As String, Byval delim as String) As Integer 

    Return Len(value) - Len(Replace(value, delim, "")) 

End Function 
相關問題