How to resolve the algorithm Count occurrences of a substring step by step in the Erlang 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 Erlang 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 Erlang programming language
Source code in the erlang programming language
%% Count non-overlapping substrings in Erlang for the rosetta code wiki.
%% Implemented by J.W. Luiten
-module(substrings).
-export([main/2]).
%% String and Sub exhausted, count a match and present result
match([], [], _OrigSub, Acc) ->
Acc+1;
%% String exhausted, present result
match([], _Sub, _OrigSub, Acc) ->
Acc;
%% Sub exhausted, count a match
match(String, [], Sub, Acc) ->
match(String, Sub, Sub, Acc+1);
%% First character matches, advance
match([X|MainTail], [X|SubTail], Sub, Acc) ->
match(MainTail, SubTail, Sub, Acc);
%% First characters do not match. Keep scanning for sub in remainder of string
match([_X|MainTail], [_Y|_SubTail], Sub, Acc)->
match(MainTail, Sub, Sub, Acc).
main(String, Sub) ->
match(String, Sub, Sub, 0).
substrings:main("ababababab","abab").
main( String, Sub ) -> erlang:length( binary:split(binary:list_to_bin(String), binary:list_to_bin(Sub), [global]) ) - 1.
You may also check:How to resolve the algorithm Bin given limits step by step in the Go programming language
You may also check:How to resolve the algorithm Metaprogramming step by step in the Rascal programming language
You may also check:How to resolve the algorithm Ruth-Aaron numbers step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Roman numerals/Encode step by step in the VBA programming language
You may also check:How to resolve the algorithm Dutch national flag problem step by step in the AutoIt programming language