How to find the index of Nth occurrence of a character in a string with VB.NET

1 Answer

0 votes
Imports System

Public Class Program
    Public Shared Function GetNthIndexOfCh(s As String, ch As Char, n As Integer) As Integer
        Dim count As Integer = 0
        
        For i As Integer = 0 To s.Length - 1
            If s(i) = ch Then
                count += 1
                If count = n Then
                    Return i
                End If
            End If
        Next

        Return -1
    End Function


    Public Shared Sub Main(ByVal args As String())
        Dim str As String = "java c++ python c# javascript"
        
        Console.WriteLine(GetNthIndexOfCh(str, "a", 3))
    End Sub
End Class



' run:
'
' 20
'

 



answered Mar 28, 2024 by avibootz
edited Mar 28, 2024 by avibootz
...