Count specific character occurrences in a string

You can try this

Dim occurCount As Integer = Len(testStr) - Len(testStr.Replace(testCharStr, ""))

The most straightforward is to simply loop through the characters in the string:

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Dim cnt As Integer = 0
  For Each c As Char In value
    If c = ch Then 
      cnt += 1
    End If
  Next
  Return cnt
End Function

Usage:

count = CountCharacter(str, "e"C)

Another approach that is almost as effective and gives shorter code is to use LINQ extension methods:

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Return value.Count(Function(c As Char) c = ch)
End Function

This is the simple way:

text = "the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3

Tags:

Vb.Net

String