What am I doing wrong?
You're finding the second a
. I'm guessing you were thinking of this:
checkme.IndexOf("a", checkme.IndexOf("a", 3))
which would actually give you the right result. (It says "Find the first a that occurs after the first a that occurs on or after the 3rd character (which happens to be an a)")
Your original code said "Find the first a which occurs on or after 3 positions beyond the first a", which only gets you to the second a
.
How do I fix it?
You could just use the IndexOf
in a loop, reusing the last found index as the next start index.
Shared Public Function FindIndexOfNthChar(ByVal checkme as String, _
ByVal checkChar as Char, _
ByVal n as Integer) as Integer
Dim lastIndex As Integer = -1
For i As Integer = 1 To n
lastIndex = checkme.IndexOf(checkChar, lastIndex + 1)
If lastIndex = -1 Then Return -1
Next i
Return lastIndex
End Function
You have to be careful; if you don't check for -1
on every attempt and exit immediately, you can end up with wrong results.
If you forgot this (as some of the other posts seem to have), then if you search for the third a
in a string with a single a
you'll actually return the index of the first a
(When you try to find the second a, you'll reset your index to -1
, which essentially starts the search over)
For that reason, it might be clearer just to write exactly what you mean:
Shared Public Function FindIndexOfNthChar(ByVal checkme as String, _
ByVal checkChar as Char, _
ByVal n as Integer) as Integer
Dim count as Integer = 0
For i as Integer = 0 To checkme.Length - 1
If(checkme(i) = checkChar) Then
count += 1
If(count = n) Then Return i
End If
Next i
return -1
End Function