4

What is the professional way to achieve this?

Thanks.

user1307346
  • 715
  • 3
  • 9
  • 14

4 Answers4

7

I've shamelessly ripped off the example from this question and converted it from C# to 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
Community
  • 1
  • 1
mclark1129
  • 7,532
  • 5
  • 48
  • 84
6

Here's a way to do it with 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

Usage:

Dim searchString As String = "Assessment"
Dim index As Integer = GetNthIndex(searchString, "s", 4) 'Returns 5
Meta-Knight
  • 17,626
  • 1
  • 48
  • 58
0

If you're going for faster:

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

Although it is slightly slower than Mike C's answer if you're looking for the nth "a" in a long string of "a"s (for example).

Edit: adjusted following spacemonkeys' comment.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • If the first chararcter (0) is the one you are looking for, and you are looking for 1, will this not miss it (i + 1) – spacemonkeys Aug 22 '12 at 21:37
0

My Version of Andew's but I believe this takes into account if the first character is the character you are looking for

 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
spacemonkeys
  • 1,689
  • 5
  • 16
  • 29