[英]Creating indices of a string in Visual Basic
如何搜索字符串以創建每次出現的字符串的索引?
例如:
“三只瞎老鼠。三只瞎老鼠。看看它們如何運轉!看看它們如何運轉!”
每當“ ee”開始時,我需要創建一個索引。
您也可以使用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
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
僅此而已的另一種解決方案!
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.