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

Source code in the coffeescript programming language

countSubstring = (str, substr) ->
  n = 0
  i = 0
  while (pos = str.indexOf(substr, i)) != -1
    n += 1
    i = pos + substr.length
  n

console.log countSubstring "the three truths", "th"
console.log countSubstring "ababababab", "abab"


  

You may also check:How to resolve the algorithm Symmetric difference step by step in the REBOL programming language
You may also check:How to resolve the algorithm Faulhaber's triangle step by step in the Racket programming language
You may also check:How to resolve the algorithm Truncate a file step by step in the Java programming language
You may also check:How to resolve the algorithm Letter frequency step by step in the SenseTalk programming language
You may also check:How to resolve the algorithm Execute a Markov algorithm step by step in the Go programming language