Count occurrences of a substring: Difference between revisions

→‎{{header|Prolog}}: version using DCG
m (→‎{{header|PHP}}: Avoiding "?>" at the end of your source file makes extra whitespace to appear less likely.)
(→‎{{header|Prolog}}: version using DCG)
Line 2,055:
X = 2.
</lang>
 
=== version using DCG ===
 
{{works with|SWI-Prolog|7.6.4}}
<lang prolog>
:- system:set_prolog_flag(double_quotes,chars) .
 
occurrences(TARGETz0,SUBSTRINGz0,COUNT)
:-
prolog:phrase(occurrences(SUBSTRINGz0,0,COUNT),TARGETz0)
.
 
occurrences("",_,_)
-->
! ,
{ false }
.
 
occurrences(SUBSTRINGz0,COUNT0,COUNT)
-->
SUBSTRINGz0 ,
! ,
{ COUNT1 is COUNT0 + 1 } ,
occurrences(SUBSTRINGz0,COUNT1,COUNT)
.
 
occurrences(SUBSTRINGz0,COUNT0,COUNT)
-->
[_] ,
! ,
occurrences(SUBSTRINGz0,COUNT0,COUNT)
.
 
occurrences(_SUBSTRINGz0_,COUNT,COUNT)
-->
!
.
 
</lang>
 
{{out}}
<pre>
/*
?- occurrences("the three truths","th",COUNT) .
COUNT = 3.
 
?- occurrences("the three truths","",COUNT) .
false .
 
?- occurrences("ababababab","abab",COUNT) .
COUNT = 2.
 
?- occurrences("ababababab","",COUNT) .
false .
 
?-
*/
 
</pre>
 
=={{header|PureBasic}}==
Anonymous user