如何搜索字符串以创建每个字符串出现的索引?
例如:
“三只盲老鼠。三只盲老鼠。看看它们是如何运行的!看看它们是如何运行的!”
每次“ee”开始时我都需要创建一个索引。
答案 0 :(得分:1)
您也可以使用Regex进行搜索。
Dim test = "Three blind mice. Three blind mice. See how they run! See how they run!"
Dim search As String = "ee"
Dim indexes As New List(Of Integer)
For Each m As Match In Regex.Matches(test, search)
indexes.Add(m.Index)
Next
答案 1 :(得分:0)
string.IndexOf有一个重载,允许扫描搜索子字符串的字符串
Dim test = "Three blind mice. Three blind mice. See how they run! See how they run!"
Dim indexes = new List(Of Integer)()
Dim pos = -1
while(true)
pos = test.IndexOf("ee", pos + 1)
if pos >= 0 then
indexes.Add(pos)
pos += 1
Else
Exit While
End if
End While
For each i in indexes
Console.WriteLine(i)
Next
只是为了好玩,另一个版本并没有在所有IndexOf上使用
Sub Main()
Dim test = "Three blind mice. Three blind mice. See how they run! See how they run!"
Dim targetValue = "mice"
Dim indexes() = AllIndexOf(test, targetValue)
for each i in indexes
Console.WriteLine(i)
Next
End Sub
Function AllIndexOf(source as string, search as string) as Integer()
Dim positions = new List(Of Integer)()
for i = 0 to source.Length-1
Dim y = i
Dim x = 0
while(x < search.Length And y+x < source.Length)
Dim c = source(y+x)
if c <> search(x) then
Exit While
End If
x +=1
End While
if x = search.Length Then
positions.Add(y)
End If
Next
return positions.ToArray()
End Function
答案 2 :(得分:-2)
另一种解决方案只是为了它的地狱!
Dim test = "Three blind mice. Three blind mice. See how they run! See how they run!"
Dim search As String = "ee"
Dim indexes As New List(Of Integer)
Dim i As Integer = test.IndexOf(search)
Do While (i <> -1)
indexes.Add(i)
i = test.IndexOf(search, i + 1)
Loop