2

Possible Duplicate:
Count specific character occurances in string

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?

Community
  • 1
  • 1
walter
  • 843
  • 2
  • 14
  • 35
  • 1
    http://stackoverflow.com/questions/5193893/count-specific-character-occurances-in-string has your answer – Marco Mar 30 '12 at 07:44
  • Your code is fine :) Perhaps make it generic by specifying the char as a parameter. – Bas Mar 30 '12 at 07:48

3 Answers3

8

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)
pingoo
  • 2,074
  • 14
  • 17
  • 2
    Nice answer, but you can remove the `.ToCharArray()` which is not needed! – Meta-Knight Mar 30 '12 at 13:07
  • 1
    I would argue that the CountChars function isn't even needed, because the code is so short. You could just call the Count method directly. – Meta-Knight Mar 30 '12 at 13:11
  • I prefer...`Value.Split("$"c).Length-1` – Carter Medlin Aug 19 '13 at 15:38
  • I suspect that my approach would be better on memory/performance as yours will create a new string for each instance of "$", where as mine will just count the instances in the existing char array. – pingoo Aug 20 '13 at 10:30
2

Simplest and most versatile way I can think of:

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

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

End Function
bendataclear
  • 3,802
  • 3
  • 32
  • 51
1

You can check the number of occurances in one more way. See the below code, if you find it better you can use that.

    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