Results 1 to 3 of 3

Thread: Counting no. of times one string appears within another

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Jul 1999
    Posts
    5,923

    Post

    Hi.

    Subject says it all really. How can i write a function to count the number of times a string such as "moo" appears in another string, such as "cows go moo a lot. Do you moo? I can moo. Everybody must moo like I moo, or the moo monster will moo at you!" which in this case is 7.

    Thanks for your assistance

    Kind regards,

    ------------------
    - Chris
    [email protected]

  2. #2
    Guru Aaron Young's Avatar
    Join Date
    Jun 1999
    Location
    Red Wing, MN, USA
    Posts
    2,177

    Post

    2 Methods:

    Both Require 2 Textboxes and a Command Button..

    1. Use the Replace Function in VB6..
    Code:
    Private Sub Command1_Click()
        Dim iNum As Long
        iNum = Len(Text1)
        iNum = (iNum - Len(Replace(LCase(Text1), LCase(Text2), ""))) / Len(Text2)
        MsgBox "The String: " & Chr(34) & Text2 & Chr(34) & " Appears in the Text " & iNum & " Times."
    End Sub
    2. Use the Instr Function..
    Code:
    Private Sub Command1_Click()
        Dim iNum As Long
        Dim iPos As Integer
        Do
            iPos = InStr(iPos + 1, LCase(Text1), LCase(Text2))
            If iPos Then iNum = iNum + 1
        Loop While iPos
        MsgBox "The String: " & Chr(34) & Text2 & Chr(34) & " Appears in the Text " & iNum & " Times."
    End Sub
    ------------------
    Aaron Young
    Analyst Programmer
    [email protected]
    [email protected]

  3. #3

    Thread Starter
    PowerPoster
    Join Date
    Jul 1999
    Posts
    5,923

    Post

    Thanks Aaron, this one was giving me jip

    Kind regards,

    ------------------
    - Chris
    [email protected]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width