VB .net - 在字符串中查找第N个char的最短和最快的方法?

时间:2012-08-22 17:13:52

标签: vb.net

实现这一目标的专业方法是什么?

感谢。

4 个答案:

答案 0 :(得分:6)

我无耻地从this question中删除了示例,并将其从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

答案 1 :(得分:6)

这是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

答案 2 :(得分:0)

如果你想要更快:

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的评论调整。

答案 3 :(得分:0)

我的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