Count occurrences of a substring

From Fōrmulæ wiki
Revision as of 13:42, 3 October 2019 by Admin (Talk | contribs) (Solution)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This page is a solution to the task Count occurrences of a substring in the Rosetta Code, written in Fōrmulæ.

Description (from Rosetta Code)


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:

  • The first argument being the string to search, and
  • The second Codea substring to be searched for.

It should return an integer count.

print countSubstring("the three truths","th")

// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")

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.



The expression Indexes returns a list of position of the occurrences of the substring. The next step is counting such that list through the Cardinality expression:

Case 1


Case 2