How to count the number of non-overlapping instances of substring in a string in VB.NET

2 Answers

0 votes
Imports System

Public Class CountNumberOfNonOverlappingInstancesOfSubstringInAString_VB_NET
    Public Shared Function countOccurrences(ByVal str As String, ByVal substr As String) As Integer
        If substr.Length = 0 Then
            Return 0
        End If

        Dim count As Integer = 0
        Dim offset As Integer = str.IndexOf(substr, StringComparison.Ordinal)

        While offset <> -1
            count += 1
            offset = str.IndexOf(substr, offset + substr.Length, StringComparison.Ordinal)
        End While

        Return count
    End Function

    Public Shared Sub Main(ByVal args As String())
		Dim s As String = "java php vb.net c# c++ python php phphp"
		
        Console.WriteLine(countOccurrences(s, "php"))
    End Sub
End Class


' run:
'
' 3
'

 



answered Aug 24, 2024 by avibootz
0 votes
Imports System

Public Class CountNumberOfNonOverlappingInstancesOfSubstringInAString_VB_NET
    Public Shared Function countOccurrences(ByVal str As String, ByVal substr As String) As Integer
        Return (str.Length - str.Replace(substr, String.Empty).Length) / substr.Length
    End Function

    Public Shared Sub Main(ByVal args As String())
		Dim s As String = "java php vb.net c# c++ python php phphp"
		
        Console.WriteLine(countOccurrences(s, "php"))
    End Sub
End Class


' run:
'
' 3
'

 



answered Aug 24, 2024 by avibootz
...