Count occurrences of a substring: Difference between revisions

Added Wren
(→‎{{header|AppleScript}}: Added the simple vanilla method.)
(Added Wren)
Line 2,589:
}</lang>
Returns: <pre>[3 2]</pre>
 
=={{header|Wren}}==
{{libheader|Wren-pattern}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/pattern" for Pattern
import "/fmt" for Fmt
 
var countSubstring = Fn.new { |str, sub|
var p = Pattern.new(sub)
return p.findAll(str).count
}
 
var tests = [
["the three truths", "th"],
["ababababab", "abab"],
["abaabba*bbaba*bbab", "a*b"],
["aaaaaaaaaaaaaa", "aa"],
["aaaaaaaaaaaaaa", "b"],
]
 
for (test in tests) {
var count = countSubstring.call(test[0], test[1])
Fmt.print("$6s occurs $d times in $q.", Fmt.q(test[1]), count, test[0])
}</lang>
 
{{out}}
<pre>
"th" occurs 3 times in "the three truths".
"abab" occurs 2 times in "ababababab".
"a*b" occurs 2 times in "abaabba*bbaba*bbab".
"aa" occurs 7 times in "aaaaaaaaaaaaaa".
"b" occurs 0 times in "aaaaaaaaaaaaaa".
</pre>
 
=={{header|XPL0}}==
9,492

edits