Link to home
Start Free TrialLog in
Avatar of explorer007
explorer007

asked on

How to find occurance of string in another string !

Hi

I need to find the 'n'th occurance of a string in a another string. It is possible to use the 'Instr' command in VB but that returns the Integer value of the location of the first occurance of the string.However take the foll. example;

"John is a good boy. John goes to school.John is a very talkative boy.John is 12 years old"

Now this string contains the word "John"
four times. If I have to parse the above mentioned string, how do I find the 3rd occurance of the word "John" in the entire string directly.

Please advise.

Cheers,
Kapil
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

You can use Instr in a loop like this:

Option Explicit

Private Sub Command1_Click()
    MsgBox FindOccurence("John is a good boy. John goes to school.John is a very talkative boy.John is 12 years old", _
                         "John", 3)
End Sub

Private Function FindOccurence(ByVal pstrText As String, _
                               ByVal pstrSearch As String, _
                               ByVal pintOccurence) As Integer
Dim intOccurence As Integer
Dim intPos As Integer

    intPos = 0
    Do While True
        intPos = InStr(intPos + 1, pstrText, pstrSearch)
        If intPos = 0 Then Exit Function
        intOccurence = intOccurence + 1
        If intOccurence = pintOccurence Then
            FindOccurence = intPos
            Exit Function
        End If
    Loop
End Function
If you use vb6

Dim str As String

str = "John is a good boy. John goes to school.John is a very talkative boy.John is 12 years old"


Dim arr

arr = Split(str, "John")
Debug.Print UBound(arr)
Debug.Print "John" & arr(3)
Erase arr


ASKER CERTIFIED SOLUTION
Avatar of PatrickVD
PatrickVD

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Lewy
Lewy

Try:
    Dim T$, X$, I As Integer, Occurance As Integer, P As Integer
    X$ = "John"
    T$ = "John is a good boy. John goes to school.John is a very talkative boy.John is 12 years old"
    Occurance = 3
    P = 1
    For I = 1 To Occurance
       P = InStr(P + 1, T$, X$)
       If P = 0 Then Exit For
    Next I
Avatar of explorer007

ASKER

Thanx ...