2012-08-22 38 views

回答

5

我無恥地從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 
+3

效率沒有羞恥! –

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 
+0

謝謝Meta-Knight – user1307346

+0

這是否考慮到*字符串中沒有* n個事件?如果他們要求第四次發生但是隻有三次? –

+0

@ChrisDunaway:我編輯了代碼,以便在沒有n次出現的情況下返回-1。 –

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 

雖然它比邁克C'S回答稍微慢一點,如果你正在尋找第N個「一「例如在一連串的」a「中。

編輯:根據spacemonkeys的評論進行調整。 Andew年代

+0

如果第一個chararcter(0)是你正在尋找的,並且你正在尋找1,這會不會錯過它(i + 1) – spacemonkeys

+0

@spacemonkeys好點。 –

0

我的版本,但我相信這是考慮到,如果第一個字符是你正在尋找

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 
相關問題