Arrays 返回字符串中单词的索引

Arrays 返回字符串中单词的索引,arrays,vb.net,vbscript,Arrays,Vb.net,Vbscript,此代码: 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")) En

此代码:

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

查看所需的输出,您似乎希望获得字符串中单词的索引。您可以通过将字符串拆分为数组,然后使用以下方法在数组中查找该项来完成此操作:

上面的代码返回2。对于猫,你会得到1,对于鸟,结果是3。如果数组中没有项,则输出为0

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)