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

Source code in the wren programming language

import "./pattern" for Pattern
import "./fmt" for Fmt

var countSubstring = Fn.new { |str, sub|
    var p = Pattern.new(sub)
    return p.findAll(str).count
}

var tests = [
    ["the three truths", "th"],
    ["ababababab", "abab"],
    ["abaabba*bbaba*bbab", "a*b"],
    ["aaaaaaaaaaaaaa", "aa"],
    ["aaaaaaaaaaaaaa", "b"],
]

for (test in tests) {
    var count = countSubstring.call(test[0], test[1])
    Fmt.print("$6s occurs $d times in $q.", Fmt.q(test[1]), count, test[0])
}

import "./str" for Str
import "./fmt" for Fmt

var tests = [
    ["the three truths", "th"],
    ["ababababab", "abab"],
    ["abaabba*bbaba*bbab", "a*b"],
    ["aaaaaaaaaaaaaa", "aa"],
    ["aaaaaaaaaaaaaa", "b"],
]

for (test in tests) {
    var count = Str.occurs(test[0], test[1])
    Fmt.print("$6s occurs $d times in $q.", Fmt.q(test[1]), count, test[0])
}

  

You may also check:How to resolve the algorithm JSON step by step in the Oforth programming language
You may also check:How to resolve the algorithm Guess the number step by step in the NS-HUBASIC programming language
You may also check:How to resolve the algorithm Palindrome detection step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Conway's Game of Life step by step in the Go programming language
You may also check:How to resolve the algorithm Thiele's interpolation formula step by step in the Mathematica / Wolfram Language programming language