此代码:
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
答案 0 :(得分:2)
查看所需的输出,您似乎想要获取字符串中的单词索引。您可以通过将字符串拆分为数组,然后使用方法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