How to resolve the algorithm Count occurrences of a substring step by step in the Gambas 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 Gambas 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 Gambas programming language

Source code in the gambas programming language

Public Sub Main() 
  
  Print countSubstring("the three truths", "th") 
  Print countSubstring("ababababab", "abab") 
  Print countSubString("zzzzzzzzzzzzzzz", "z")

End 

Function countSubstring(s As String, search As String) As Integer 

  If s = "" Or search = "" Then Return 0 
  Dim count As Integer = 0, length As Integer = Len(search) 
  For i As Integer = 1 To Len(s) 
    If Mid(s, i, length) = Search Then 
      count += 1 
      i += length - 1 
    End If 
  Next 
  Return count 

End Function


  

You may also check:How to resolve the algorithm Benford's law step by step in the Phix programming language
You may also check:How to resolve the algorithm Terminal control/Clear the screen step by step in the M2000 Interpreter programming language
You may also check:How to resolve the algorithm Musical scale step by step in the Ursa programming language
You may also check:How to resolve the algorithm Hamming numbers step by step in the ZX Spectrum Basic programming language
You may also check:How to resolve the algorithm Plasma effect step by step in the Scala programming language