Count occurrences of a substring: Difference between revisions

(Added Elixir)
Line 1,449:
say count-substring("ababababab","abab");</lang>
Note that in Perl 6 the <tt>/$little/</tt> matches the variable literally, so there's no need to quote regex metacharacters. Also, prefix <tt>+</tt> forces numeric context in Perl&nbsp;6 (it's a no-op in Perl&nbsp;5). One other style point: we now tend to prefer hyphenated names over camelCase.
 
=={{header|Phix}}==
<lang Phix>sequence tests = {{"the three truths","th"},
{"ababababab","abab"},
{"ababababab","aba"},
{"ababababab","ab"},
{"ababababab","a"},
{"ababababab",""}}
integer start, count
string test, substring
for i=1 to length(tests) do
start = 1
count = 0
{test, substring} = tests[i]
while 1 do
start = match(substring,test,start)
if start=0 then exit end if
start += length(substring)
count += 1
end while
printf(1,"The string \"%s\" occurs as a non-overlapping substring %d times in \"%s\"\n",{substring,count,test})
end for</lang>
{{out}}
<pre>
The string "th" occurs as a non-overlapping substring 3 times in "the three truths"
The string "abab" occurs as a non-overlapping substring 2 times in "ababababab"
The string "aba" occurs as a non-overlapping substring 2 times in "ababababab"
The string "ab" occurs as a non-overlapping substring 5 times in "ababababab"
The string "a" occurs as a non-overlapping substring 5 times in "ababababab"
The string "" occurs as a non-overlapping substring 0 times in "ababababab"
</pre>
 
=={{header|PHP}}==
7,820

edits