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

Source code in the txr programming language

@(next :args)
@(do (defun count-occurrences (haystack needle)
       (for* ((occurrences 0)
              (old-pos 0)
              (new-pos (search-str haystack needle old-pos nil)))
             (new-pos occurrences)
             ((inc occurrences)
              (set old-pos (+ new-pos (length needle)))
              (set new-pos (search-str haystack needle old-pos nil))))))
@ndl
@hay
@(output)
@(count-occurrences hay ndl) occurrences(s) of @ndl inside @hay
@(end)

  

You may also check:How to resolve the algorithm Zeckendorf number representation step by step in the Nim programming language
You may also check:How to resolve the algorithm Text processing/2 step by step in the Fortran programming language
You may also check:How to resolve the algorithm 100 doors step by step in the Eiffel programming language
You may also check:How to resolve the algorithm Sum of a series step by step in the Panda programming language
You may also check:How to resolve the algorithm Arithmetic numbers step by step in the Raku programming language