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

Source code in the fsharp programming language

open System

let countSubstring (where :string) (what : string) =
    match what with
    | "" -> 0 // just a definition; infinity is not an int
    | _ -> (where.Length - where.Replace(what, @"").Length) / what.Length
    

[<EntryPoint>]
let main argv =
    let show where what =
        printfn @"countSubstring(""%s"", ""%s"") = %d" where what (countSubstring where what)
    show "the three truths" "th"
    show "ababababab" "abab"
    show "abc" ""
    0


  

You may also check:How to resolve the algorithm Disarium numbers step by step in the Rust programming language
You may also check:How to resolve the algorithm Exceptions step by step in the Ursa programming language
You may also check:How to resolve the algorithm Program termination step by step in the AArch64 Assembly programming language
You may also check:How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the AWK programming language
You may also check:How to resolve the algorithm Find common directory path step by step in the Oz programming language