Visual Basic .NET » Classic Visual Basic
Count how many times a string occurs in a text string? -- prendster --

I have a newbie question here. How to count a substring occurs in a text string?

E.g :
I have a string : "This is not about me but this is about him"

I want to count how many times the word "is" are occur?
Simple solution for finding a substring in visual basic -- laurent --

So do you want find a substring occurs in a text string?

I got this code from other forum, maybe this will help you..

Function CountSubString(StringIn As String, SubString As String) As Long
Dim pos As Long
pos = InStr(StringIn, SubString)
Do While pos
CountSubString = CountSubString + 1
pos = pos + Len(SubString)
If pos < Len(StringIn) Then
pos = Instr(pos, StringIn, SubString)
Else
Exit Do
End If
Loop
End Function
 


Above code maybe too long and slower...maybe you can try this code:

Public Function lCount(sStr As String, sSubStr As String) As Long
' Count occurrences of sSubStr in sStr
If Len(sSubStr) <> 0 Then
lCount = (Len(sStr) - Len(Replace(sStr, sSubStr, ""))) /
Len(sSubStr)
End If
End Function
 


For simple and fast function you can try this code:

Public Function lCount(sStr As String, sSubStr As String) As Long
If Len(sStr) Then lCount = UBound(Split(sStr, sSubStr))
End Function
 
[Submit Comment]Home