如何获取字符串中某些字符的位置?
示例:my string = "你好,你在做什么"
我想从那些应该返回位置号4、13和 17 的字符串中返回o 的位置。我尝试过str.IndexOf但它只返回o的第一次出现。
这是我尝试过的:
Dim str = "hello, what you doing"
Dim dIndex = str.IndexOf("o")
If (dIndex > -1) Then
Console.WriteLine(dIndex.toString())
End If
任何方法都可以。
我正在使用 Visual Studio 2008。
因此,一旦找到第一个匹配字符的位置,就可以告诉它从该位置之后继续查找。
在这里,我创建了一个返回位置列表的函数。(如果没有匹配项,则列表将为空。)
Option Strict On
Option Infer On
Module Module1
Function IndexesOf(s As String, c As Char) As List(Of Integer)
Dim positions As New List(Of Integer)
Dim pos = s.IndexOf(c)
While pos >= 0
positions.Add(pos)
pos = s.IndexOf(c, pos + 1)
End While
Return positions
End Function
Sub Main()
Dim os = IndexesOf("hello, what you doing", "o"c)
For Each pos In os
Console.WriteLine(pos)
Next
Console.ReadLine()
End Sub
End Module
输出:
4
13
17
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句