【问题标题】:VB .net - shortest and fastest way to find Nth occurrence of char in string?VB .net - 在字符串中找到第 N 次出现的字符的最短和最快方法?
【发布时间】:2012-08-22 17:13:52
【问题描述】:

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

谢谢。

【问题讨论】:

  • 专业的方式是获得报酬。
  • 最短的代码,最快的算法,最节省内存的算法,最可读的代码?
  • @SteveDog - 请最短最快。
  • 你不能同时拥有。做出选择。
  • 如果您正在寻找最快,我想说@MikeC 的答案与您将获得的一样快(除了索引等更极端的措施之外)。

标签: vb.net


【解决方案1】:

我无耻地从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

【讨论】:

  • 效率不丢人!
【解决方案2】:

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

【讨论】:

  • 这是否考虑到字符串中没有 n 次出现?如果他们要求第 4 次出现但只有 3 次怎么办?
  • @ChrisDunaway:我编辑了代码,以便在没有出现 n 的情况下返回 -1。
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    如果你想要更快:

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

    【讨论】:

    • 如果第一个字符 (0) 是你要找的那个,而你要找 1,这会不会错过它 (i + 1)
    猜你喜欢
    • 2016-08-07
    • 2011-02-04
    • 2011-08-06
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 2012-04-25
    相关资源
    最近更新 更多