Error_2646
Error_2646

Reputation: 3791

How to get all indexes of search string

I have a loop that kind of works, but the values at each index change once the loop exits.

Expected Input: ("Test Testing Tested","test")

Expected Output: {1,6,14}

Function charIndexes(Optional ByVal inputStr As String = "test testing testicle", Optional searchStr As String = "test") As Variant

    Dim cI() As Integer
    Dim matchCnt As Integer

    matchCnt = 0
    pos = 1

    Do Until InStr(pos, inputStr, searchStr) = 0

        ReDim cI(matchCnt + 1)
        cI(matchCnt) = InStr(pos, inputStr, searchStr)
        MsgBox "cI(" & CStr(matchCnt) & ") = " & CStr(cI(matchCnt)) ' This outputs what I want


        pos = InStr(pos, inputStr, searchStr) + 1
        matchCnt = matchCnt + 1

    Loop

    For i = 0 To 2

        MsgBox "cI(" & CStr(i) & ") = " & CStr(cI(i)) ' This outputs nonsense - {0,0,14}
        Next i

    charIndexes = cI

End Function

Sub testFuncs()

    testResult = charIndexes()

End Sub

Why are the values of cI at each index not the same inside the loop as outside?

Upvotes: 0

Views: 160

Answers (1)

user2299169
user2299169

Reputation:

You overwrite your array with Redim (so all values get defaulted to 0 - the last will return the proper value, as that's the only one you actually set). You should do a Redim Preserve instead of ReDim. Something like:

matchCnt = 0
pos = 1

ReDim cI(1) 'Initial size, otherwise preserve will fail
Do Until InStr(pos, inputStr, searchStr) = 0

    ReDim Preserve cI(matchCnt + 1)
    cI(matchCnt) = InStr(pos, inputStr, searchStr)
    MsgBox "cI(" & CStr(matchCnt) & ") = " & CStr(cI(matchCnt))

    pos = InStr(pos, inputStr, searchStr) + 1
    matchCnt = matchCnt + 1
Loop

Upvotes: 1

Related Questions