Count occurrences of a substring: Difference between revisions

Line 2,610:
=={{header|Red}}==
<lang Red>Red []
 
;;-----------------------------------
count-sub1occurrences: funcfunction [haystring needlesubstring] [
length? parse string [collect [some [keep substring to substring]]]
;;-----------------------------------
prin rejoin ["hay: " pad copy hay 20 ",needle: " pad copy needle 6 ",count: " ]
i: 0
parse hay [ some [thru needle (i: i + 1)] ]
print i
]
 
;;-----------------------------------
counttest-sub1case-1: "the three truths" "th"
count-sub2: func [hay needle][
counttest-sub1case-2: "ababababab" "abab"
;;-----------------------------------
 
prin rejoin ["hay: " pad copy hay 20 ",needle: " pad copy needle 6 ",count: " ]
print [test-case-1 "-" count-occurrences test-case-1 "th"]
i: 0
print [test-case-2 "-" count-occurrences test-case-2 "abab"]
while [hay: find hay needle][
i: i + 1
hay: skip hay length? needle
]
print i
]
count-sub1 "the three truths" "th"
count-sub1 "ababababab" "abab"
print "^/version 2"
count-sub2 "the three truths" "th"
count-sub2 "ababababab" "abab"
</lang>
{{out}}
<pre>hay: the three truths ,needle: th ,count:- 3
hay: ababababab ,needle: abab ,count:- 2
>> </pre>
 
version 2
hay: the three truths ,needle: th ,count: 3
hay: ababababab ,needle: abab ,count: 2
>> </pre>
 
=={{header|REXX}}==