Vb.net: 在一个大字符串中记录pattern的多个Index

Vb.net: Recording multiple Indexes of pattern in a large string

我目前被困在一个项目中,在该项目中我得到了一个大的随机字符串,例如:“C AF EE D D B EE F”(可能超过 900 个字符),我必须获得多个实例的索引一个模式,然后将它们存储到一个动态数组中。

就像我需要模式的索引 "EE",应该是 8 和 18(我想?)。然后我需要将这些索引记录在动态数组中,例如 "EE_Array()"

我找到了这段代码:

    Dim i As Integer = 0
    Dim EE_Array() As String
    Dim SearchWithinThis As String = "  C   AF   EE   D B EE   F"
    Dim SearchForThis As String = "EE"
    Dim First As Integer = SearchWithinThis.IndexOf(SearchForThis)
    Dim Array(i) = First

然后我重复代码,搜索另一个模式,将其存储在另一个数组中。

效果很好,但仅适用于第一个实例。我需要把它放在一个循环中并增加 i 和 redim 保留数组使其更大并继续前进直到它到达字符串的末尾(我认为是 -1)。

试试下面的代码

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim SearchWithinThis As String = "  C   AF   EE   D B EE   F"
    Dim SearchForThis As String = "EE"

    Dim Indexes As List(Of Integer) = GetIndexes(SearchWithinThis, SearchForThis)

    Dim EE_Array() As Integer = Indexes.ToArray
End Sub

Private Function GetIndexes(ByVal SearchWithinThis As String, ByVal SearchForThis As String) As List(Of Integer)
    Dim Result As New List(Of Integer)

    Dim i As Integer = SearchWithinThis.IndexOf(SearchForThis)

    While (i <> -1)
        Result.Add(i)
        i = SearchWithinThis.IndexOf(SearchForThis, i + 1)
    End While

    Return Result
End Function

函数 GetIndexes returns 包含索引的整数列表