Wednesday, June 20, 2012

VB.NET - Count Number of Characters in a String


Public Function CharCount(ByVal OrigString As String, ByVal Chars As String, Optional ByVal CaseSensitive As Boolean = False) As Integer

        '**********************************************
        '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

        'EXAMPLES:
        'Debug.Print CharCount("FreeVBCode.com", "E") -- returns 3
        'Debug.Print CharCount("FreeVBCode.com", "E", True) -- returns 0
        'Debug.Print CharCount("FreeVBCode.com", "co") -- returns 2
        ''**********************************************

        Dim intLen As Integer
        Dim intCharLen As Integer
        Dim intAns As Integer
        Dim strInput As String
        Dim strChar As String
        Dim intCtr As Integer
        Dim intEndOfLoop As Integer
        Dim bytCompareType As Byte

        strInput = OrigString
        If strInput = "" Then Exit Function
        intLen = Len(strInput)
        intCharLen = Len(Chars)
        intEndOfLoop = (intLen - intCharLen) + 1
        bytCompareType = CByte(IIf(CaseSensitive, vbBinaryCompare, vbTextCompare))

        For lCtr = 1 To intEndOfLoop
            strChar = Mid(strInput, lCtr, intCharLen)
            If StrComp(strChar, Chars, CType(bytCompareType, CompareMethod)) = 0 Then _
                intAns = intAns + 1
        Next

        CharCount = intAns

    End Function




** Originally Retrieved From: http://www.freevbcode.com/ShowCode.asp?ID=1025 (I modified to be an int)