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

Source code in the algol programming language

#!/usr/local/bin/a68g --script #

PROC count string in string = (STRING needle, haystack)INT: (
  INT start:=LWB haystack, next, out:=0;
  FOR count WHILE string in string(needle, next, haystack[start:]) DO
    start+:=next+UPB needle-LWB needle;
    out:=count
  OD;
  out
);

printf(($d" "$,
  count string in string("th", "the three truths"),    # expect 3 #
  count string in string("abab", "ababababab"),        # expect 2 #
  count string in string("a*b", "abaabba*bbaba*bbab"), # expect 2 #
  $l$
))

  

You may also check:How to resolve the algorithm Filter step by step in the Octave programming language
You may also check:How to resolve the algorithm Word frequency step by step in the Ruby programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the UnixPipes programming language
You may also check:How to resolve the algorithm Loops/Foreach step by step in the Lambdatalk programming language
You may also check:How to resolve the algorithm Undefined values step by step in the BASIC programming language