Return 单词在字符串中的索引
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
Return 字符串中的起始位置 5
但是如何 return 字符串的索引 so:
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)
上面的代码 returns 2. 对于猫,你会得到 1,对于鸟,结果将为 3。如果数组中没有项目,输出将为 0
此代码:
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
Return 字符串中的起始位置 5
但是如何 return 字符串的索引 so:
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)
上面的代码 returns 2. 对于猫,你会得到 1,对于鸟,结果将为 3。如果数组中没有项目,输出将为 0