How to resolve the algorithm Count occurrences of a substring step by step in the Visual Basic .NET programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Count occurrences of a substring step by step in the Visual Basic .NET programming language

Table of Contents

Problem Statement

Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:

It should return an integer count. The matching should yield the highest number of non-overlapping matches. In general, this essentially means matching from left-to-right or right-to-left   (see proof on talk page).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Count occurrences of a substring step by step in the Visual Basic .NET programming language

Source code in the visual programming language

Module Count_Occurrences_of_a_Substring
    Sub Main()
        Console.WriteLine(CountSubstring("the three truths", "th"))
        Console.WriteLine(CountSubstring("ababababab", "abab"))
        Console.WriteLine(CountSubstring("abaabba*bbaba*bbab", "a*b"))
        Console.WriteLine(CountSubstring("abc", ""))
    End Sub

    Function CountSubstring(str As String, substr As String) As Integer
        Dim count As Integer = 0
        If (Len(str) > 0) And (Len(substr) > 0) Then
            Dim p As Integer = InStr(str, substr)
            Do While p <> 0
                p = InStr(p + Len(substr), str, substr)
                count += 1
            Loop
        End If
        Return count
    End Function
End Module

  

You may also check:How to resolve the algorithm Archimedean spiral step by step in the Phix programming language
You may also check:How to resolve the algorithm Rot-13 step by step in the Modula-2 programming language
You may also check:How to resolve the algorithm Strip comments from a string step by step in the AutoIt programming language
You may also check:How to resolve the algorithm Random number generator (included) step by step in the Tcl programming language
You may also check:How to resolve the algorithm Ulam spiral (for primes) step by step in the Go programming language