簡體   English   中英

返回字符串中單詞的索引

[英]Return index of word in string

這段代碼:

Module Module1
    Sub Main()
    ' Our input string.
    Dim animals As String = "cat, dog, bird"

    ' See if dog is contained in the string.
    If Not animals.IndexOf("dog") = -1 Then
        Console.WriteLine(animals.IndexOf("dog"))
    End If
    End Sub
End Module

返回字符串中的起始位置5

但是如何返回字符串的索引呢:

for cat = 1
for dog = 2
for bird = 3

查看所需的輸出,看來您想獲取字符串中單詞的索引。 您可以通過將字符串拆分為數組,然后使用Array.FindIndex方法在數組中查找項目來做到這一點

Dim animals = "cat, dog, bird"

' Split string to array
Dim animalsArray = animals.Split(New String() {",", " "}, StringSplitOptions.RemoveEmptyEntries)

' Item to find
Dim itemToFind = "dog"
' Find index in array
Dim index = Array.FindIndex(Of String)(animalsArray, Function(s) s = itemToFind)
' Add 1 to the output:
Console.WriteLine(index + 1)

上面的代碼返回2。對於cat,您將得到1;對於bird,結果將是3。如果數組中沒有項目,則輸出將為0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM