+ Reply to Thread
Results 1 to 3 of 3

Counting SubStrings and thier starting positions within Main Strin

  1. #1
    ExcelMonkey
    Guest

    Counting SubStrings and thier starting positions within Main Strin

    What is the easiest way to count the number of occurences of a substring
    within a string AND the starting position of each substring? For Example:

    String = "dog 123 cat 452 if 6754 dog"
    SubString = "dog"

    Occurences of SubString = 2
    Starting Position of SubString = 1 and 26

    Thanks

    EM

  2. #2
    Toppers
    Guest

    RE: Counting SubStrings and thier starting positions within Main Strin

    One way:

    Public npos() as integer

    Sub GetSubStrings(ByVal SearchString As String, FindStr As String)
    n = 1
    i = 0
    Do
    n = InStr(n, SearchString, FindStr)
    If n <> 0 Then
    ReDim Preserve Npos(i)
    Npos(i) = n
    n = n + 1
    i = i + 1
    End If
    Loop Until n = 0
    End Sub

    Sub myTest()

    Call GetSubStrings("dog 123 cat 452 if 6754 dog", "dog")

    MsgBox "Number of strings = " & UBound(Npos) + 1
    For i = 0 To UBound(Npos)
    MsgBox Npos(i)
    Next
    End Sub

    "ExcelMonkey" wrote:

    > What is the easiest way to count the number of occurences of a substring
    > within a string AND the starting position of each substring? For Example:
    >
    > String = "dog 123 cat 452 if 6754 dog"
    > SubString = "dog"
    >
    > Occurences of SubString = 2
    > Starting Position of SubString = 1 and 26
    >
    > Thanks
    >
    > EM


  3. #3
    Bob Phillips
    Guest

    Re: Counting SubStrings and thier starting positions within Main Strin

    cTimes = (Len(sString) - Len(Replace(sString, sSubstring, ""))) _
    / Len(sSubstring)
    sMsg = sSubstring & " occurs" & cTimes & " times" & vbNewLine
    ipos = 0
    For i = 1 To cTimes
    ipos = InStr(ipos + 1, sString, sSubstring)
    sMsg = sMsg & "#" & i & " occurs at: " & ipos & vbNewLine
    Next i

    MsgBox sMsg


    --

    HTH

    Bob Phillips

    (remove nothere from the email address if mailing direct)

    "ExcelMonkey" <[email protected]> wrote in message
    news:[email protected]...
    > What is the easiest way to count the number of occurences of a substring
    > within a string AND the starting position of each substring? For Example:
    >
    > String = "dog 123 cat 452 if 6754 dog"
    > SubString = "dog"
    >
    > Occurences of SubString = 2
    > Starting Position of SubString = 1 and 26
    >
    > Thanks
    >
    > EM




+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1