How to resolve the algorithm Count occurrences of a substring step by step in the OCaml 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 OCaml 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 OCaml programming language
Source code in the ocaml programming language
let count_substring str sub =
let sub_len = String.length sub in
let len_diff = (String.length str) - sub_len
and reg = Str.regexp_string sub in
let rec aux i n =
if i > len_diff then n else
try
let pos = Str.search_forward reg str i in
aux (pos + sub_len) (succ n)
with Not_found -> n
in
aux 0 0
let () =
Printf.printf "count 1: %d\n" (count_substring "the three truth" "th");
Printf.printf "count 2: %d\n" (count_substring "ababababab" "abab");
;;
You may also check:How to resolve the algorithm Blum integer step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Hello world/Graphical step by step in the batari Basic programming language
You may also check:How to resolve the algorithm Top rank per group step by step in the Erlang programming language
You may also check:How to resolve the algorithm Evaluate binomial coefficients step by step in the C++ programming language
You may also check:How to resolve the algorithm Factorial primes step by step in the Nim programming language