在 Visual Basic (VB) 中,你可以使用 IndexOf 方法来查找一个字符或子字符串在字符串中的位置。 IndexOf 方法返回匹配项的第一个索引,如果没有找到匹配项,则返回 -1。
下面土嘎嘎小编分享一些示例来获取字符在字符串中的位置:
1. 使用 IndexOf 获取字符的位置:
〓〓vb代码如下:〓〓
Dim str As String = "Hello World"
Dim index As Integer = str.IndexOf("o") ' 查找字符 "o" 的位置
Console.WriteLine(index) ' 输出:4
2. 使用 IndexOf 获取子字符串的位置:
〓〓vb代码如下:〓〓
Dim str As String = "Hello World"
Dim index As Integer = str.IndexOf("World") ' 查找子字符串 "World" 的位置
Console.WriteLine(index) ' 输出:6
3. 使用循环和 IndexOf 获取所有匹配项的位置:
〓〓vb代码如下:〓〓
Dim str As String = "Hello World"
Dim searchChar As Char = "o"
Dim indices As New List(Of Integer)()
Dim currentIndex As Integer = str.IndexOf(searchChar)
While currentIndex <> -1
indices.Add(currentIndex)
currentIndex = str.IndexOf(searchChar, currentIndex + 1)
End While
For Each index As Integer In indices
Console.WriteLine(index)
Next
上面给出的示例演示了如何使用 IndexOf 方法在字符串中查找字符或子字符串的位置。根据你的需求,你可以通过修改参数来搜索不同的字符或子字符串,并使用返回的索引进行后续操作。