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

Source code in the standard programming language

fun count_substrings (str, sub) =
  let
    fun aux (str', count) =
      let
        val suff = #2 (Substring.position sub str')
      in
        if Substring.isEmpty suff then
       	  count
        else
          aux (Substring.triml (size sub) suff, count + 1)
      end
  in
    aux (Substring.full str, 0)
  end;

print (Int.toString (count_substrings ("the three truths", "th")) ^ "\n");
print (Int.toString (count_substrings ("ababababab", "abab")) ^ "\n");
print (Int.toString (count_substrings ("abaabba*bbaba*bbab", "a*b")) ^ "\n");


  

You may also check:How to resolve the algorithm Variadic function step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm Search a list step by step in the Ring programming language
You may also check:How to resolve the algorithm Product of min and max prime factors step by step in the Cowgol programming language
You may also check:How to resolve the algorithm Square-free integers step by step in the Swift programming language
You may also check:How to resolve the algorithm Run-length encoding step by step in the M2000 Interpreter programming language