Count Specific Character Occurrences in String


strText = "QTP Sreenu Blog"
strChar = "e"'Counting the number of occurrences of e

Using Split Function

MsgBoxUBound(Split(UCase(strText),UCase(strChar)))

Using Len Funtion

MsgBox (Len(strText)-Len(Replace(UCase(strText),UCase(strChar),"")))

Using Len & Mid Functions

iLen = Len(strText)
iCount=0
For i=1To iLen
    IfStrComp(UCase(strChar),UCase(Mid(strText,i,1)))=0Then
        iCount = iCount+1
    EndIf
Next
MsgBox iCount

Using Len & InStr Functions

iLen = Len(strText)
iCount=0
i=0
DoWhile i<iLen
    iCharPosition = InStr(i+1,UCase(strText),UCase(strChar))
    If iCharPosition>0Then
        iCount = iCount+1
        i = iCharPosition
    Else
        ExitDo
    EndIf
Loop
MsgBox iCount

Without using any built-in functions

iCount = 0
Set oRegExp = NewRegExp
oRegExp.Pattern = "\d|\D|\s|\S|\t|\w|\W"'This pattern matches with any character
oRegExp.Global = True
Set oItems = oRegExp.Execute(strText)
For i=0To oItems.Count-1
    IfUCase(oItems(i)) = UCase(strChar) Then
        iCount = iCount+1
    EndIf
Next
MsgBox iCount

No comments:

Post a Comment