Imports System
Module MainModule
' Non‑overlapping occurrences are matches of a substring that do not reuse any of
' the same characters. Once one match is counted, the next search must begin
' after that match ends.
Function count_non_overlapping(haystack As String, needle As String) As Integer
'
' Count how many times 'needle' appears in 'haystack' without overlapping.
' The algorithm:
' • Use String.IndexOf() to locate the next occurrence.
' • Each time a match is found, move the search index forward
' by the full length of the matched substring.
' • This ensures no characters are reused between matches.
'
Dim count As Integer = 0
Dim index As Integer = 0 ' current search position in the main string
' Continue searching until IndexOf() returns -1 (meaning: no more matches)
While True
' Find the next occurrence starting at the current index
Dim pos As Integer = haystack.IndexOf(needle, index)
If pos = -1 Then
' No more matches found
Exit While
End If
' We found a match, so increment the count
count += 1
' Move index forward by the length of the needle
' This ensures the next search begins *after* the matched substring
index = pos + needle.Length
End While
Return count
End Function
' ---------------------------------------------------------------
Sub Main()
' Demonstration using the string provided in the instructions:
Dim s As String = "go java phphp rust c pphpp c++ phpphp python php phphp"
Dim substring As String = "php"
' Count non-overlapping occurrences
Dim result As Integer = count_non_overlapping(s, substring)
Console.WriteLine("Non-overlapping occurrences: " & result)
End Sub
End Module
'
' run:
'
' Non-overlapping occurrences: 6
'