Difference between revisions of "Count occurrences of a substring"

From Fōrmulæ wiki
Jump to: navigation, search
(Creation of page)
 
(Solution)
 
Line 25: Line 25:
  
 
=== Solution ===
 
=== Solution ===
 
The expression [[String.Indexes|Indexes]] returns a list of position of the occurrences of the substring. The next step is counting such that list through the [[Expression.Cardinality|Cardinality]] expression:
 
  
 
[[File:CountOccurrencesSubStringCode.png|border]]
 
[[File:CountOccurrencesSubStringCode.png|border]]
 +
 +
The expression [[String.Indexes|Indexes]] returns a list of position of the occurrences of the substring. The next step is counting such that list through the [[Expression.Cardinality|Cardinality]] expression:
  
 
=== Case 1 ===
 
=== Case 1 ===

Latest revision as of 13:42, 3 October 2019

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)

Task

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")
3

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

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.

Solution

CountOccurrencesSubStringCode.png

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

CountOccurrencesSubStringCase01.png

Case 2

CountOccurrencesSubStringCase02.png