Friday, July 3, 2009

Number of occurances of a character or character sequence in a string

PURPOSE: Returns Number of occurrences of a character or
or a character sequencence within a string

PARAMETERS:
OrigString: String to Search in
Chars: Character(s) to search for
CaseSensitive (Optional): Do a case sensitive search
Defaults to false

RETURNS:
Number of Occurrences of Chars in OrigString



Public Function CharCount(OrigString As String, _
Chars As String, Optional CaseSensitive As Boolean = False) _
As Long


Dim lLen As Long
Dim lCharLen As Long
Dim lAns As Long
Dim sInput As String
Dim sChar As String
Dim lCtr As Long
Dim lEndOfLoop As Long
Dim bytCompareType As Byte

sInput = OrigString
If sInput = "" Then Exit Function
lLen = Len(sInput)
lCharLen = Len(Chars)
lEndOfLoop = (lLen - lCharLen) + 1
bytCompareType = IIf(CaseSensitive, vbBinaryCompare, _
vbTextCompare)

For lCtr = 1 To lEndOfLoop
sChar = Mid(sInput, lCtr, lCharLen)
If StrComp(sChar, Chars, bytCompareType) = 0 Then _
lAns = lAns + 1
Next

CharCount = lAns

End Function




EXAMPLES:
CharCount("Dotnetspider", "E") -- returns 2
CharCount("Dotnetspider", "E", True) -- returns 0

No comments:

Post a Comment