如何获取搜索字符串的所有索引

时间:2016-05-20 18:17:59

标签: vba

我有一个循环,但是一旦循环退出,每个索引的值都会改变。

预期输入:("测试测试测试","测试")

预期产出:{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

为什么每个索引的cI值在循环内部与外部不一样?

1 个答案:

答案 0 :(得分:1)

你用Redim覆盖你的数组(所以所有的值都默认为0 - 最后一个会返回正确的值,因为那是你实际设置的唯一值)。你应该做一个Redim Preserve而不是ReDim。类似的东西:

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