Friday, April 24, 2009

Count Character Occurances In a String

In a string occurance of particular character can be found easily by using the function 'InStr()' which returns the location of the character in the string. But if we want to count the number of occurances of particular character in the string then I've found the following three ways to get the

Private Function countOccurance1(ByVal hayStack As String,ByVal needle As Char) As Integer
If String.IsNullOrEmpty(hayStack) Then Return 0
Dim chars() As Char = hayStack.ToCharArray
Dim count As Integer = 0
For Each ch As Char In chars
If ch = needle Then count += 1
Next
Return count

End Function

Private Function countOccurance2(ByVal hayStack As String, ByVal needle As String) As Integer
Return (Len(hayStack) - Len(Replace(hayStack, needle, ""))) / Len(needle)
End Function

Private Function countOccurance3(ByVal hayStack As String, ByVal needle As String) As Integer
Dim i As Long, sHayStack As String : sHayStack = hayStack
Do Until InStr(sHayStack, needle) = 0
sHayStack = Replace(sHayStack, needle, "", 1, 1) : i += 1
Loop
Return i

End Function

I've not tested which is more effiecient, but all provides the similar results for many number tests.

No comments: