实现这一目标的专业方法是什么?
谢谢。
我无耻地从这个问题中扯掉了这个例子,并将它从 C# 转换为 VB.net。
Public Function GetNthIndex(s As String, t As Char, n As Integer) As Integer
Dim count As Integer = 0
For i As Integer = 0 To s.Length - 1
If s(i) = t Then
count += 1
If count = n Then
Return i
End If
End If
Next
Return -1
End Function
这是使用 Linq 的一种方法。
Public Function GetNthIndex(searchString As String, charToFind As Char, n As Integer) As Integer
Dim charIndexPair = searchString.Select(Function(c,i) new with {.Character = c, .Index = i}) _
.Where(Function(x) x.Character = charToFind) _
.ElementAtOrDefault(n-1)
Return If(charIndexPair IsNot Nothing, charIndexPair.Index, -1)
End Function
用法:
Dim searchString As String = "Assessment"
Dim index As Integer = GetNthIndex(searchString, "s", 4) 'Returns 5
如果你想要更快:
Public Function NthIndexOf(s As String, c As Char, n As Integer) As Integer
Dim i As Integer = -1
Dim count As Integer = 0
While count < n AndAlso i >= 0
i = s.IndexOf(c, i + 1)
count += 1
End While
Return i
End Function
尽管如果您要在一长串“a”中寻找第 n 个“a”(例如),它比 Mike C 的回答要慢一些。
编辑:根据 spacemonkeys 的评论进行了调整。
我的 Andew 版本,但我相信这会考虑到第一个字符是否是您正在寻找的字符
Public Function GetNthIndexStringFunc(s As String, t As String, n As Integer) As Integer
Dim newFound As Integer = -1
For i As Integer = 1 To n
newFound = s.IndexOf(t, newFound + 1)
If newFound = -1 Then
Return newFound
End If
Next
Return newFound
End Function