Count occurrences of a substring: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 10: Line 10:


It should return an integer count.
It should return an integer count.
<lang pseudocode>print countSubstring("the three truths","th")
<syntaxhighlight lang="pseudocode">print countSubstring("the three truths","th")
3
3


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


The matching should yield the highest number of non-overlapping matches.
The matching should yield the highest number of non-overlapping matches.
Line 26: Line 26:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>print(‘the three truths’.count(‘th’))
<syntaxhighlight lang="11l">print(‘the three truths’.count(‘th’))
print(‘ababababab’.count(‘abab’))</lang>
print(‘ababababab’.count(‘abab’))</syntaxhighlight>


{{out}}
{{out}}
Line 37: Line 37:
=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
The program uses two ASSIST macros (XDECO,XPRNT) to keep the code as short as possible.
The program uses two ASSIST macros (XDECO,XPRNT) to keep the code as short as possible.
<lang 360asm>* Count occurrences of a substring 05/07/2016
<syntaxhighlight lang="360asm">* Count occurrences of a substring 05/07/2016
COUNTSTR CSECT
COUNTSTR CSECT
USING COUNTSTR,R13 base register
USING COUNTSTR,R13 base register
Line 102: Line 102:
* ---- -------------------------------------------------------
* ---- -------------------------------------------------------
YREGS
YREGS
END COUNTSTR</lang>
END COUNTSTR</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 115: Line 115:
<code>DE</code>.
<code>DE</code>.


<lang 8080asm> org 100h
<syntaxhighlight lang="8080asm"> org 100h
jmp demo
jmp demo
;;; Count non-overlapping substrings (BC) in string (HL)
;;; Count non-overlapping substrings (BC) in string (HL)
Line 170: Line 170:
sub2: db 'abab',0 ; result should be 2
sub2: db 'abab',0 ; result should be 2
str3: db 'cat',0
str3: db 'cat',0
sub3: db 'dog',0 ; result should be 0</lang>
sub3: db 'dog',0 ; result should be 0</syntaxhighlight>


{{out}}
{{out}}
Line 177: Line 177:


=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==
<lang asm> cpu 8086
<syntaxhighlight lang="asm"> cpu 8086
org 100h
org 100h
section .text
section .text
Line 242: Line 242:
.sub2: db 'abab',0 ; result should be 2
.sub2: db 'abab',0 ; result should be 2
.str3: db 'cat',0
.str3: db 'cat',0
.sub3: db 'dog',0 ; result should be 0</lang>
.sub3: db 'dog',0 ; result should be 0</syntaxhighlight>


{{out}}
{{out}}
Line 249: Line 249:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>BYTE FUNC CountSubstring(CHAR ARRAY s,sub)
<syntaxhighlight lang="action!">BYTE FUNC CountSubstring(CHAR ARRAY s,sub)
BYTE i,j,res,found
BYTE i,j,res,found


Line 285: Line 285:
Test("11111111","11")
Test("11111111","11")
Test("abcdefg","123")
Test("abcdefg","123")
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Count_occurrences_of_a_substring.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Count_occurrences_of_a_substring.png Screenshot from Atari 8-bit computer]
Line 296: Line 296:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Strings.Fixed, Ada.Integer_Text_IO;
<syntaxhighlight lang="ada">with Ada.Strings.Fixed, Ada.Integer_Text_IO;


procedure Substrings is
procedure Substrings is
Line 304: Line 304:
Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => "ababababab",
Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => "ababababab",
Pattern => "abab"));
Pattern => "abab"));
end Substrings;</lang>
end Substrings;</syntaxhighlight>


{{out}}
{{out}}
Line 314: Line 314:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
Algol68 has no build in function to do this task, hence the next to create a ''count string in string'' routine.
Algol68 has no build in function to do this task, hence the next to create a ''count string in string'' routine.
<lang algol68>#!/usr/local/bin/a68g --script #
<syntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #


PROC count string in string = (STRING needle, haystack)INT: (
PROC count string in string = (STRING needle, haystack)INT: (
Line 330: Line 330:
count string in string("a*b", "abaabba*bbaba*bbab"), # expect 2 #
count string in string("a*b", "abaabba*bbaba*bbab"), # expect 2 #
$l$
$l$
))</lang>
))</syntaxhighlight>


<pre>
<pre>
Line 338: Line 338:
=={{header|Apex}}==
=={{header|Apex}}==
Apex example for 'Count occurrences of a substring'.
Apex example for 'Count occurrences of a substring'.
<syntaxhighlight lang="apex">
<lang Apex>
String substr = 'ABC';
String substr = 'ABC';
String str = 'ABCZZZABCYABCABCXXABC';
String str = 'ABCZZZABCYABCABCXXABC';
Line 350: Line 350:
}
}
System.debug('Count String : '+count);
System.debug('Count String : '+count);
</syntaxhighlight>
</lang>


<pre>
<pre>
Line 359: Line 359:
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}


<lang apl>csubs←{0=x←⊃⍸⍺⍷⍵:0 ⋄ 1+⍺∇(¯1+x+⍴⍺)↓⍵}</lang>
<syntaxhighlight lang="apl">csubs←{0=x←⊃⍸⍺⍷⍵:0 ⋄ 1+⍺∇(¯1+x+⍴⍺)↓⍵}</syntaxhighlight>


{{out}}
{{out}}
Line 375: Line 375:
Here we use a generic ''evalOSA(language, code)'' function to apply a JavaScript for Automation regex to a pair of AppleScript strings, using OSAKit.
Here we use a generic ''evalOSA(language, code)'' function to apply a JavaScript for Automation regex to a pair of AppleScript strings, using OSAKit.


<lang AppleScript>use framework "OSAKit"
<syntaxhighlight lang="applescript">use framework "OSAKit"


on run
on run
Line 403: Line 403:
return oError's NSLocalizedDescription as text
return oError's NSLocalizedDescription as text
end evalOSA</lang>
end evalOSA</syntaxhighlight>


{{out}}
{{out}}
Line 412: Line 412:
The above assertions notwithstanding, it's always been possible to use AppleScript's text item delimiters for this purpose with its native strings, except that the TIDs have only observed the current considering/ignoring state with the 'unicode text' class, which was introduced around Mac OS X 10.4 and became AppleScript's only native text class with the introduction of AppleScript 2.0 in Mac OS X 10.5.
The above assertions notwithstanding, it's always been possible to use AppleScript's text item delimiters for this purpose with its native strings, except that the TIDs have only observed the current considering/ignoring state with the 'unicode text' class, which was introduced around Mac OS X 10.4 and became AppleScript's only native text class with the introduction of AppleScript 2.0 in Mac OS X 10.5.


<lang applescript>on countSubstring(theString, theSubstring)
<syntaxhighlight lang="applescript">on countSubstring(theString, theSubstring)
set astid to AppleScript's text item delimiters
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to theSubstring
set AppleScript's text item delimiters to theSubstring
Line 421: Line 421:
end countSubstring
end countSubstring


{countSubstring("the three truths", "th"), countSubstring("ababababab", "abab")}</lang>
{countSubstring("the three truths", "th"), countSubstring("ababababab", "abab")}</syntaxhighlight>


{{Out}}
{{Out}}
<lang applescript>{3, 2}</lang>
<syntaxhighlight lang="applescript">{3, 2}</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>countOccurrences: function [str, substr]-> size match str substr
<syntaxhighlight lang="rebol">countOccurrences: function [str, substr]-> size match str substr


loop [["the three truths" "th"] ["ababababab" "abab"]] 'pair ->
loop [["the three truths" "th"] ["ababababab" "abab"]] 'pair ->
Line 434: Line 434:
~"occurrences of '|last pair|' in '|first pair|':"
~"occurrences of '|last pair|' in '|first pair|':"
countOccurrences first pair last pair
countOccurrences first pair last pair
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 445: Line 445:
AutoHotkey has a rather unconventional method which outperforms this.
AutoHotkey has a rather unconventional method which outperforms this.
StringReplace sets the number of replaced strings to ErrorLevel.
StringReplace sets the number of replaced strings to ErrorLevel.
<lang AutoHotkey>MsgBox % countSubstring("the three truths","th") ; 3
<syntaxhighlight lang="autohotkey">MsgBox % countSubstring("the three truths","th") ; 3
MsgBox % countSubstring("ababababab","abab") ; 2
MsgBox % countSubstring("ababababab","abab") ; 2


Line 451: Line 451:
StringReplace, junk, fullstring, %substring%, , UseErrorLevel
StringReplace, junk, fullstring, %substring%, , UseErrorLevel
return errorlevel
return errorlevel
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==


<syntaxhighlight lang="awk">#
<lang AWK>#
# countsubstring(string, pattern)
# countsubstring(string, pattern)
# Returns number of occurrences of pattern in string
# Returns number of occurrences of pattern in string
Line 484: Line 484:
print countsubstring_regex("[do&d~run?d!run&>run&]", "run[&]")
print countsubstring_regex("[do&d~run?d!run&>run&]", "run[&]")
print countsubstring("the three truths","th")
print countsubstring("the three truths","th")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>$ awk -f countsubstring.awk
<pre>$ awk -f countsubstring.awk
Line 493: Line 493:


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang qbasic>FUNCTION Uniq_Tally(text$, part$)
<syntaxhighlight lang="qbasic">FUNCTION Uniq_Tally(text$, part$)
LOCAL x
LOCAL x
WHILE TALLY(text$, part$)
WHILE TALLY(text$, part$)
Line 503: Line 503:


PRINT "the three truths - th: ", Uniq_Tally("the three truths", "th")
PRINT "the three truths - th: ", Uniq_Tally("the three truths", "th")
PRINT "ababababab - abab: ", Uniq_Tally("ababababab", "abab")</lang>
PRINT "ababababab - abab: ", Uniq_Tally("ababababab", "abab")</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 515: Line 515:
In FreeBASIC, this needs to be compiled with <code>-lang qb</code> or <code>-lang fblite</code>.
In FreeBASIC, this needs to be compiled with <code>-lang qb</code> or <code>-lang fblite</code>.


<lang qbasic>DECLARE FUNCTION countSubstring& (where AS STRING, what AS STRING)
<syntaxhighlight lang="qbasic">DECLARE FUNCTION countSubstring& (where AS STRING, what AS STRING)


PRINT "the three truths, th:", countSubstring&("the three truths", "th")
PRINT "the three truths, th:", countSubstring&("the three truths", "th")
Line 529: Line 529:
LOOP
LOOP
countSubstring = c
countSubstring = c
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


{{out}}
{{out}}
Line 538: Line 538:


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic>10 F$ = "TH"
<syntaxhighlight lang="applesoftbasic">10 F$ = "TH"
20 S$ = "THE THREE TRUTHS"
20 S$ = "THE THREE TRUTHS"
30 GOSUB 100"COUNT SUBSTRING
30 GOSUB 100"COUNT SUBSTRING
Line 557: Line 557:
170 IF F$ = MID$(S$, I, F) THEN R = R + 1 : I = I + F - 1
170 IF F$ = MID$(S$, I, F) THEN R = R + 1 : I = I + F - 1
180 NEXT I
180 NEXT I
190 RETURN</lang>
190 RETURN</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 INPUT PROMPT "String: ":TXT$
<syntaxhighlight lang="is-basic">100 INPUT PROMPT "String: ":TXT$
110 INPUT PROMPT "Substring: ":SUB$
110 INPUT PROMPT "Substring: ":SUB$
120 PRINT COUNT(LCASE$(TXT$),LCASE$(SUB$))
120 PRINT COUNT(LCASE$(TXT$),LCASE$(SUB$))
Line 570: Line 570:
180 LOOP UNTIL PO=0
180 LOOP UNTIL PO=0
190 LET COUNT=N
190 LET COUNT=N
200 END DEF</lang>
200 END DEF</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM.
Works with 1k of RAM.
<lang basic> 10 LET S$="THE THREE TRUTHS"
<syntaxhighlight lang="basic"> 10 LET S$="THE THREE TRUTHS"
20 LET U$="TH"
20 LET U$="TH"
30 GOSUB 100
30 GOSUB 100
Line 590: Line 590:
150 LET N=N+1
150 LET N=N+1
160 LET I=I+LEN U$
160 LET I=I+LEN U$
170 GOTO 130</lang>
170 GOTO 130</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
{{trans|QBasic}}
{{trans|QBasic}}
<lang qbasic>FUNCTION countsubstring(where$, what$)
<syntaxhighlight lang="qbasic">FUNCTION countsubstring(where$, what$)
LET c = 0
LET c = 0
LET s = 1-LEN(what$)
LET s = 1-LEN(what$)
Line 607: Line 607:
PRINT "the three truths, th:", countSubstring("the three truths", "th")
PRINT "the three truths, th:", countSubstring("the three truths", "th")
PRINT "ababababab, abab:", countSubstring("ababababab", "abab")
PRINT "ababababab, abab:", countSubstring("ababababab", "abab")
END</lang>
END</syntaxhighlight>


==={{header|BASIC256}}===
==={{header|BASIC256}}===
{{trans|Run BASIC}}
{{trans|Run BASIC}}
<lang freebasic>print countSubstring("the three truths","th")
<syntaxhighlight lang="freebasic">print countSubstring("the three truths","th")
print countSubstring("ababababab","abab")
print countSubstring("ababababab","abab")
end
end
Line 621: Line 621:
i = instr(s$,find$,i) + length(find$)
i = instr(s$,find$,i) + length(find$)
end while
end while
end function</lang>
end function</syntaxhighlight>
{{out}}
{{out}}
<pre>Igual que la entrada de Run BASIC.</pre>
<pre>Igual que la entrada de Run BASIC.</pre>
Line 627: Line 627:
==={{header|Yabasic}}===
==={{header|Yabasic}}===
{{trans|Run BASIC}}
{{trans|Run BASIC}}
<lang yabasic>print countSubstring("the three truths","th")
<syntaxhighlight lang="yabasic">print countSubstring("the three truths","th")
print countSubstring("ababababab","abab")
print countSubstring("ababababab","abab")
end
end
Line 639: Line 639:
end while
end while
return countSubstring
return countSubstring
end sub</lang>
end sub</syntaxhighlight>
{{out}}
{{out}}
<pre>Igual que la entrada de Run BASIC.</pre>
<pre>Igual que la entrada de Run BASIC.</pre>
Line 645: Line 645:


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
setlocal enabledelayedexpansion


Line 665: Line 665:
set input=!trimmed!
set input=!trimmed!
set /a cnt+=1
set /a cnt+=1
goto count_loop</lang>
goto count_loop</syntaxhighlight>
{{Out}}
{{Out}}
<pre>3
<pre>3
Line 671: Line 671:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> tst$ = "the three truths"
<syntaxhighlight lang="bbcbasic"> tst$ = "the three truths"
sub$ = "th"
sub$ = "th"
PRINT ; FNcountSubstring(tst$, sub$) " """ sub$ """ in """ tst$ """"
PRINT ; FNcountSubstring(tst$, sub$) " """ sub$ """ in """ tst$ """"
Line 687: Line 687:
UNTIL I% = 0
UNTIL I% = 0
= N%
= N%
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>3 "th" in "the three truths"
<pre>3 "th" in "the three truths"
Line 693: Line 693:


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


let countsubstr(str, match) = valof
let countsubstr(str, match) = valof
Line 721: Line 721:
show("ababababab", "abab")
show("ababababab", "abab")
show("cat", "dog")
show("cat", "dog")
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>"th" in "the three truths": 3
<pre>"th" in "the three truths": 3
Line 729: Line 729:
=={{header|BQN}}==
=={{header|BQN}}==
<code>/𝕨⍷𝕩</code> finds locations of substrings, rest of the function suppresses overlapping substrings.
<code>/𝕨⍷𝕩</code> finds locations of substrings, rest of the function suppresses overlapping substrings.
<lang bqn>Find←{i←/𝕨⍷𝕩, i/˜i≥»0≤◶⟨⊣,(≠𝕨)+⊢⟩`i}
<syntaxhighlight lang="bqn">Find←{i←/𝕨⍷𝕩, i/˜i≥»0≤◶⟨⊣,(≠𝕨)+⊢⟩`i}


•Show "abab" Find "ababababab"
•Show "abab" Find "ababababab"
•Show "th" Find "the three truths"</lang>
•Show "th" Find "the three truths"</syntaxhighlight>
<lang>2
<syntaxhighlight lang="text">2
3</lang>
3</syntaxhighlight>


Using strings.bqn from bqn-libs, another solution is <code>Find←+´Locate</code>, since <code>Locate</code> performs a non-overlapping search.
Using strings.bqn from bqn-libs, another solution is <code>Find←+´Locate</code>, since <code>Locate</code> performs a non-overlapping search.


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat> ( count-substring
<syntaxhighlight lang="bracmat"> ( count-substring
= n S s p
= n S s p
. 0:?n:?p
. 0:?n:?p
Line 754: Line 754:
& out$(count-substring$("the three truths".th))
& out$(count-substring$("the three truths".th))
& out$(count-substring$(ababababab.abab))
& out$(count-substring$(ababababab.abab))
& ;</lang>
& ;</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 760: Line 760:


=={{header|C}}==
=={{header|C}}==
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <string.h>


Line 781: Line 781:
printf("not: %d\n", match("abababababa", "aba", 0));
printf("not: %d\n", match("abababababa", "aba", 0));
return 0;
return 0;
}</lang>
}</syntaxhighlight>


Alternate version:
Alternate version:
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <string.h>


Line 805: Line 805:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 814: Line 814:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang c sharp>using System;
<syntaxhighlight lang="c sharp">using System;


class SubStringTestClass
class SubStringTestClass
Line 839: Line 839:
return count;
return count;
}
}
}</lang>
}</syntaxhighlight>


Using C# 6.0's expression-bodied member, null-conditional operator, and coalesce operator features:
Using C# 6.0's expression-bodied member, null-conditional operator, and coalesce operator features:


<lang c sharp>using System;
<syntaxhighlight lang="c sharp">using System;
class SubStringTestClass
class SubStringTestClass
{
{
public static int CountSubStrings(this string testString, string testSubstring) =>
public static int CountSubStrings(this string testString, string testSubstring) =>
testString?.Split(new [] { testSubstring }, StringSplitOptions.None)?.Length - 1 ?? 0;
testString?.Split(new [] { testSubstring }, StringSplitOptions.None)?.Length - 1 ?? 0;
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <string>


Line 874: Line 874:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 884: Line 884:
=={{header|Clojure}}==
=={{header|Clojure}}==
Use a sequence of regexp matches to count occurrences.
Use a sequence of regexp matches to count occurrences.
<lang clojure>
<syntaxhighlight lang="clojure">
(defn re-quote
(defn re-quote
"Produces a string that can be used to create a Pattern
"Produces a string that can be used to create a Pattern
Line 895: Line 895:
(defn count-substring [txt sub]
(defn count-substring [txt sub]
(count (re-seq (re-pattern (re-quote sub)) txt)))
(count (re-seq (re-pattern (re-quote sub)) txt)))
</syntaxhighlight>
</lang>


Use the trick of blank replacement and maths to count occurrences.
Use the trick of blank replacement and maths to count occurrences.
<lang clojure>
<syntaxhighlight lang="clojure">
(defn count-substring1 [txt sub]
(defn count-substring1 [txt sub]
(/ (- (count txt) (count (.replaceAll txt sub "")))
(/ (- (count txt) (count (.replaceAll txt sub "")))
(count sub)))
(count sub)))
</syntaxhighlight>
</lang>


A Java 8 stream-based solution, which should avoid creation of temporary strings
A Java 8 stream-based solution, which should avoid creation of temporary strings
(though it will produce temporary MatchResult instances).
(though it will produce temporary MatchResult instances).
<lang clojure>
<syntaxhighlight lang="clojure">
(defn count-substring2 [txt sub]
(defn count-substring2 [txt sub]
(-> sub
(-> sub
Line 914: Line 914:
(.results)
(.results)
(.count)))
(.count)))
</syntaxhighlight>
</lang>


=={{header|COBOL}}==
=={{header|COBOL}}==
<code>INSPECT</code> can be used for this task without having to create a function.
<code>INSPECT</code> can be used for this task without having to create a function.
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. testing.
PROGRAM-ID. testing.


Line 939: Line 939:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


{{out}}
{{out}}
Line 949: Line 949:


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
countSubstring = (str, substr) ->
countSubstring = (str, substr) ->
n = 0
n = 0
Line 960: Line 960:
console.log countSubstring "the three truths", "th"
console.log countSubstring "the three truths", "th"
console.log countSubstring "ababababab", "abab"
console.log countSubstring "ababababab", "abab"
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun count-sub (str pat)
<syntaxhighlight lang="lisp">(defun count-sub (str pat)
(loop with z = 0 with s = 0 while s do
(loop with z = 0 with s = 0 while s do
(when (setf s (search pat str :start2 s))
(when (setf s (search pat str :start2 s))
Line 970: Line 970:


(count-sub "ababa" "ab") ; 2
(count-sub "ababa" "ab") ; 2
(count-sub "ababa" "aba") ; 1</lang>
(count-sub "ababa" "aba") ; 1</syntaxhighlight>


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


sub countSubstring(str: [uint8], match: [uint8]): (count: uint8) is
sub countSubstring(str: [uint8], match: [uint8]): (count: uint8) is
Line 999: Line 999:
print_nl();
print_nl();
print_i8(countSubstring("cat","dog")); # should print 0
print_i8(countSubstring("cat","dog")); # should print 0
print_nl();</lang>
print_nl();</syntaxhighlight>


{{out}}
{{out}}
Line 1,008: Line 1,008:


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm;
import std.stdio, std.algorithm;


"the three truths".count("th").writeln;
"the three truths".count("th").writeln;
"ababababab".count("abab").writeln;
"ababababab".count("abab").writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,019: Line 1,019:


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program OccurrencesOfASubstring;
<syntaxhighlight lang="delphi">program OccurrencesOfASubstring;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,041: Line 1,041:
Writeln(CountSubstring('the three truths', 'th'));
Writeln(CountSubstring('the three truths', 'th'));
Writeln(CountSubstring('ababababab', 'abab'));
Writeln(CountSubstring('ababababab', 'abab'));
end.</lang>
end.</syntaxhighlight>


=={{header|Dyalect}}==
=={{header|Dyalect}}==


<lang dyalect>func countSubstring(str, val) {
<syntaxhighlight lang="dyalect">func countSubstring(str, val) {
var idx = 0
var idx = 0
var count = 0
var count = 0
Line 1,060: Line 1,060:


print(countSubstring("the three truths", "th"))
print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))</lang>
print(countSubstring("ababababab", "abab"))</syntaxhighlight>


{{out}}
{{out}}
Line 1,068: Line 1,068:


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>!. count "the three truths" "th"
<syntaxhighlight lang="dejavu">!. count "the three truths" "th"
!. count "ababababab" "abab"</lang>
!. count "ababababab" "abab"</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,075: Line 1,075:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
;; from Racket
;; from Racket
(define count-substring
(define count-substring
Line 1,084: Line 1,084:
(count-substring "/ .e/" "Longtemps je me suis couché de bonne heure") ;; regexp
(count-substring "/ .e/" "Longtemps je me suis couché de bonne heure") ;; regexp
→ 4
→ 4
</syntaxhighlight>
</lang>


=={{header|EGL}}==
=={{header|EGL}}==
{{works with|EDT}}
{{works with|EDT}}
The "remove and count the difference" and "manual loop" methods. Implementation includes protection from empty source and search strings.
The "remove and count the difference" and "manual loop" methods. Implementation includes protection from empty source and search strings.
<lang EGL>program CountStrings
<syntaxhighlight lang="egl">program CountStrings
function main()
function main()
Line 1,140: Line 1,140:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Remove and Count:
<pre>Remove and Count:
Line 1,162: Line 1,162:


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<lang eiffel>
<syntaxhighlight lang="eiffel">
class
class
APPLICATION
APPLICATION
Line 1,198: Line 1,198:
search_for:STRING = "abab"
search_for:STRING = "abab"
end
end
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>countSubstring = fn(_, "") -> 0
<syntaxhighlight lang="elixir">countSubstring = fn(_, "") -> 0
(str, sub) -> length(String.split(str, sub)) - 1 end
(str, sub) -> length(String.split(str, sub)) - 1 end


Line 1,215: Line 1,215:
Enum.each(data, fn{str, sub} ->
Enum.each(data, fn{str, sub} ->
IO.puts countSubstring.(str, sub)
IO.puts countSubstring.(str, sub)
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,230: Line 1,230:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
%% Count non-overlapping substrings in Erlang for the rosetta code wiki.
%% Count non-overlapping substrings in Erlang for the rosetta code wiki.
%% Implemented by J.W. Luiten
%% Implemented by J.W. Luiten
Line 1,258: Line 1,258:
main(String, Sub) ->
main(String, Sub) ->
match(String, Sub, Sub, 0).</lang>
match(String, Sub, Sub, 0).</syntaxhighlight>
Command: <lang Erlang>substrings:main("ababababab","abab").</lang>
Command: <syntaxhighlight lang="erlang">substrings:main("ababababab","abab").</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,266: Line 1,266:


Alternative using built in functions:
Alternative using built in functions:
<syntaxhighlight lang="erlang">
<lang Erlang>
main( String, Sub ) -> erlang:length( binary:split(binary:list_to_bin(String), binary:list_to_bin(Sub), [global]) ) - 1.
main( String, Sub ) -> erlang:length( binary:split(binary:list_to_bin(String), binary:list_to_bin(Sub), [global]) ) - 1.
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function countSubstring(sequence s, sequence sub)
<syntaxhighlight lang="euphoria">function countSubstring(sequence s, sequence sub)
integer from,count
integer from,count
count = 0
count = 0
Line 1,287: Line 1,287:


? countSubstring("the three truths","th")
? countSubstring("the three truths","th")
? countSubstring("ababababab","abab")</lang>
? countSubstring("ababababab","abab")</syntaxhighlight>


{{out}}
{{out}}
Line 1,296: Line 1,296:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
"Remove and count the difference" method, as shown by J, Java, ...
"Remove and count the difference" method, as shown by J, Java, ...
<lang Fsharp>open System
<syntaxhighlight lang="fsharp">open System


let countSubstring (where :string) (what : string) =
let countSubstring (where :string) (what : string) =
Line 1,311: Line 1,311:
show "ababababab" "abab"
show "ababababab" "abab"
show "abc" ""
show "abc" ""
0</lang>
0</syntaxhighlight>
<pre>countSubstring("the three truths", "th") = 3
<pre>countSubstring("the three truths", "th") = 3
countSubstring("ababababab", "abab") = 2
countSubstring("ababababab", "abab") = 2
Line 1,317: Line 1,317:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: math sequences splitting ;
<syntaxhighlight lang="factor">USING: math sequences splitting ;
: occurences ( seq subseq -- n ) split-subseq length 1 - ;</lang>
: occurences ( seq subseq -- n ) split-subseq length 1 - ;</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: str-count ( s1 len s2 len -- n )
<syntaxhighlight lang="forth">: str-count ( s1 len s2 len -- n )
2swap 0 >r
2swap 0 >r
begin 2over search
begin 2over search
Line 1,329: Line 1,329:


s" the three truths" s" th" str-count . \ 3
s" the three truths" s" th" str-count . \ 3
s" ababababab" s" abab" str-count . \ 2</lang>
s" ababababab" s" abab" str-count . \ 2</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>program Example
<syntaxhighlight lang="fortran">program Example
implicit none
implicit none
integer :: n
integer :: n
Line 1,360: Line 1,360:
end do
end do
end function
end function
end program</lang>
end program</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,367: Line 1,367:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Function countSubstring(s As String, search As String) As Integer
Function countSubstring(s As String, search As String) As Integer
Line 1,386: Line 1,386:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,396: Line 1,396:


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>import util.Regex
<syntaxhighlight lang="funl">import util.Regex


def countSubstring( str, substr ) = Regex( substr ).findAllMatchIn( str ).length()
def countSubstring( str, substr ) = Regex( substr ).findAllMatchIn( str ).length()


println( countSubstring("the three truths", "th") )
println( countSubstring("the three truths", "th") )
println( countSubstring("ababababab", "abab") )</lang>
println( countSubstring("ababababab", "abab") )</syntaxhighlight>


{{out}}
{{out}}
Line 1,420: Line 1,420:
=={{header|Go}}==
=={{header|Go}}==
Using strings.Count() method:
Using strings.Count() method:
<lang go>package main
<syntaxhighlight lang="go">package main
import (
import (
"fmt"
"fmt"
Line 1,429: Line 1,429:
fmt.Println(strings.Count("the three truths", "th")) // says: 3
fmt.Println(strings.Count("the three truths", "th")) // says: 3
fmt.Println(strings.Count("ababababab", "abab")) // says: 2
fmt.Println(strings.Count("ababababab", "abab")) // says: 2
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Solution, uses the Groovy "find" operator (=~), and the Groovy-extended Matcher property "count":
Solution, uses the Groovy "find" operator (=~), and the Groovy-extended Matcher property "count":
<lang groovy>println (('the three truths' =~ /th/).count)
<syntaxhighlight lang="groovy">println (('the three truths' =~ /th/).count)
println (('ababababab' =~ /abab/).count)
println (('ababababab' =~ /abab/).count)
println (('abaabba*bbaba*bbab' =~ /a*b/).count)
println (('abaabba*bbaba*bbab' =~ /a*b/).count)
println (('abaabba*bbaba*bbab' =~ /a\*b/).count)</lang>
println (('abaabba*bbaba*bbab' =~ /a\*b/).count)</syntaxhighlight>


{{out}}
{{out}}
Line 1,446: Line 1,446:
=={{header|Haskell}}==
=={{header|Haskell}}==
=== Text-based solution ===
=== Text-based solution ===
<lang haskell>import Data.Text hiding (length)
<syntaxhighlight lang="haskell">import Data.Text hiding (length)


-- Return the number of non-overlapping occurrences of sub in str.
-- Return the number of non-overlapping occurrences of sub in str.
Line 1,454: Line 1,454:
print $ countSubStrs "the three truths" "th"
print $ countSubStrs "the three truths" "th"
print $ countSubStrs "ababababab" "abab"
print $ countSubStrs "ababababab" "abab"
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,462: Line 1,462:


Alternatively, in a language built around currying, it might make more sense to reverse the suggested order of arguments.
Alternatively, in a language built around currying, it might make more sense to reverse the suggested order of arguments.
<lang haskell>{-# LANGUAGE OverloadedStrings #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}


import Data.Text hiding (length)
import Data.Text hiding (length)
Line 1,481: Line 1,481:
"abelian absurdity",
"abelian absurdity",
"babel kebab"
"babel kebab"
]</lang>
]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[5,2,2]</pre>
<pre>[5,2,2]</pre>
Line 1,488: Line 1,488:
Even though list-based strings are not "the right" way of representing texts, the problem of counting subsequences in a list is generally useful.
Even though list-based strings are not "the right" way of representing texts, the problem of counting subsequences in a list is generally useful.


<lang Haskell>count :: Eq a => [a] -> [a] -> Int
<syntaxhighlight lang="haskell">count :: Eq a => [a] -> [a] -> Int
count [] = error "empty substring"
count [] = error "empty substring"
count sub = go
count sub = go
Line 1,496: Line 1,496:
scan [] xs = 1 + go xs
scan [] xs = 1 + go xs
scan (x:xs) (y:ys) | x == y = scan xs ys
scan (x:xs) (y:ys) | x == y = scan xs ys
| otherwise = go ys</lang>
| otherwise = go ys</syntaxhighlight>
{{Out}}
{{Out}}
<pre>λ> count "th" "the three truths"
<pre>λ> count "th" "the three truths"
Line 1,510: Line 1,510:
The following solution is almost two times faster than the previous one.
The following solution is almost two times faster than the previous one.


<lang Haskell>import Data.List (tails, stripPrefix)
<syntaxhighlight lang="haskell">import Data.List (tails, stripPrefix)
import Data.Maybe (catMaybes)
import Data.Maybe (catMaybes)


count :: Eq a => [a] -> [a] -> Int
count :: Eq a => [a] -> [a] -> Int
count sub = length . catMaybes . map (stripPrefix sub) . tails</lang>
count sub = length . catMaybes . map (stripPrefix sub) . tails</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
every A := ![ ["the three truths","th"], ["ababababab","abab"] ] do
every A := ![ ["the three truths","th"], ["ababababab","abab"] ] do
write("The string ",image(A[2])," occurs as a non-overlapping substring ",
write("The string ",image(A[2])," occurs as a non-overlapping substring ",
Line 1,530: Line 1,530:
}
}
return c
return c
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 1,538: Line 1,538:
=={{header|J}}==
=={{header|J}}==


<lang j>require'strings'
<syntaxhighlight lang="j">require'strings'
countss=: #@] %~ #@[ - [ #@rplc '';~]</lang>
countss=: #@] %~ #@[ - [ #@rplc '';~]</syntaxhighlight>


In other words: find length of original string, replace the string to be counted with the empty string, find the difference in lengths and divide by the length of the string to be counted.
In other words: find length of original string, replace the string to be counted with the empty string, find the difference in lengths and divide by the length of the string to be counted.
Line 1,545: Line 1,545:
Example use:
Example use:


<lang j> 'the three truths' countss 'th'
<syntaxhighlight lang="j"> 'the three truths' countss 'th'
3
3
'ababababab' countss 'abab'
'ababababab' countss 'abab'
2</lang>
2</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
The "remove and count the difference" method:
The "remove and count the difference" method:
<lang java>public class CountSubstring {
<syntaxhighlight lang="java">public class CountSubstring {
public static int countSubstring(String subStr, String str){
public static int countSubstring(String subStr, String str){
return (str.length() - str.replace(subStr, "").length()) / subStr.length();
return (str.length() - str.replace(subStr, "").length()) / subStr.length();
Line 1,563: Line 1,563:
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,571: Line 1,571:
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
The "split and count" method:
The "split and count" method:
<lang java>import java.util.regex.Pattern;
<syntaxhighlight lang="java">import java.util.regex.Pattern;


public class CountSubstring {
public class CountSubstring {
Line 1,585: Line 1,585:
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,592: Line 1,592:


Manual looping
Manual looping
<lang java>public class CountSubstring {
<syntaxhighlight lang="java">public class CountSubstring {
public static int countSubstring(String subStr, String str){
public static int countSubstring(String subStr, String str){
int count = 0;
int count = 0;
Line 1,606: Line 1,606:
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,614: Line 1,614:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
Using regexes:
Using regexes:
<lang javascript>function countSubstring(str, subStr) {
<syntaxhighlight lang="javascript">function countSubstring(str, subStr) {
var matches = str.match(new RegExp(subStr, "g"));
var matches = str.match(new RegExp(subStr, "g"));
return matches ? matches.length : 0;
return matches ? matches.length : 0;
}</lang>
}</syntaxhighlight>


Using 'split' and ES6 notation:
Using 'split' and ES6 notation:
<lang javascript>const countSubString = (str, subStr) => str.split(subStr).length - 1;
<syntaxhighlight lang="javascript">const countSubString = (str, subStr) => str.split(subStr).length - 1;
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
Using regexes (available in jq versions after June 19, 2014):
Using regexes (available in jq versions after June 19, 2014):
<syntaxhighlight lang="jq">
<lang jq>
def countSubstring(sub):
def countSubstring(sub):
[match(sub; "g")] | length;</lang>Example:<lang jq>
[match(sub; "g")] | length;</syntaxhighlight>Example:<syntaxhighlight lang="jq">
"the three truths" | countSubstring("th")</lang>
"the three truths" | countSubstring("th")</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Line 1,639: Line 1,639:


'''Main'''
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
ts = ["the three truths", "ababababab"]
ts = ["the three truths", "ababababab"]
tsub = ["th", "abab"]
tsub = ["th", "abab"]
Line 1,654: Line 1,654:
println(length(matchall(Regex(tsub[i]), ts[i], true)))
println(length(matchall(Regex(tsub[i]), ts[i], true)))
end
end
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,669: Line 1,669:
=={{header|K}}==
=={{header|K}}==
The dyadic verb _ss gives the positions of substring y in string x.
The dyadic verb _ss gives the positions of substring y in string x.
<lang K> "the three truths" _ss "th"
<syntaxhighlight lang="k"> "the three truths" _ss "th"
0 4 13
0 4 13


Line 1,680: Line 1,680:
#"ababababab" _ss "abab"
#"ababababab" _ss "abab"
2
2
</syntaxhighlight>
</lang>


=={{header|Klingphix}}==
=={{header|Klingphix}}==
<lang Klingphix>include ..\Utilitys.tlhy
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy


:count %s !s
:count %s !s
Line 1,695: Line 1,695:
"ababababab" "abab" count ?
"ababababab" "abab" count ?


" " input</lang>
" " input</syntaxhighlight>
Other solution
Other solution
<lang Klingphix>include ..\Utilitys.tlhy
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy


:count "- " convert "-" 2 tolist split len nip ;
:count "- " convert "-" 2 tolist split len nip ;
Line 1,704: Line 1,704:
"ababababab" "abab" count ?
"ababababab" "abab" count ?


" " input</lang>
" " input</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,710: Line 1,710:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun countSubstring(s: String, sub: String): Int = s.split(sub).size - 1
fun countSubstring(s: String, sub: String): Int = s.split(sub).size - 1
Line 1,718: Line 1,718:
println(countSubstring("ababababab","abab"))
println(countSubstring("ababababab","abab"))
println(countSubstring("",""))
println(countSubstring("",""))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,728: Line 1,728:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{def countSubstring
{def countSubstring
{def countSubstring.r
{def countSubstring.r
Line 1,752: Line 1,752:
{countSubstring aba ababa}
{countSubstring aba ababa}
-> 1
-> 1
</syntaxhighlight>
</lang>


=={{header|langur}}==
=={{header|langur}}==
<lang langur>writeln len indices q(th), q(the three truths)
<syntaxhighlight lang="langur">writeln len indices q(th), q(the three truths)
writeln len indices q(abab), q(ababababab)</lang>
writeln len indices q(abab), q(ababababab)</syntaxhighlight>


{{out}}
{{out}}
Line 1,763: Line 1,763:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define countSubstring(str::string, substr::string)::integer => {
<syntaxhighlight lang="lasso">define countSubstring(str::string, substr::string)::integer => {
local(i = 1, foundpos = -1, found = 0)
local(i = 1, foundpos = -1, found = 0)
while(#i < #str->size && #foundpos != 0) => {
while(#i < #str->size && #foundpos != 0) => {
Line 1,788: Line 1,788:
//3
//3
countSubstring_bothways('ababababab','abab')
countSubstring_bothways('ababababab','abab')
//2</lang>
//2</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print countSubstring( "the three truths", "th")
print countSubstring( "the three truths", "th")
print countSubstring( "ababababab", "abab")
print countSubstring( "ababababab", "abab")
Line 1,805: Line 1,805:
countSubstring =c
countSubstring =c
end function
end function
</syntaxhighlight>
</lang>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
Using atoms for string representation:
Using atoms for string representation:
<lang logtalk>
<syntaxhighlight lang="logtalk">
:- object(counting).
:- object(counting).


Line 1,827: Line 1,827:


:- end_object.
:- end_object.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang text>
<syntaxhighlight lang="text">
| ?- counting::count('the three truths', th, N).
| ?- counting::count('the three truths', th, N).
N = 3
N = 3
Line 1,837: Line 1,837:
N = 2
N = 2
yes
yes
</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==
Solution 1:
Solution 1:


<lang Lua>function countSubstring(s1, s2)
<syntaxhighlight lang="lua">function countSubstring(s1, s2)
return select(2, s1:gsub(s2, ""))
return select(2, s1:gsub(s2, ""))
end
end


print(countSubstring("the three truths", "th"))
print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))</lang>
print(countSubstring("ababababab", "abab"))</syntaxhighlight>
<pre>3
<pre>3
2</pre>
2</pre>
Line 1,854: Line 1,854:
Solution 2:
Solution 2:


<lang Lua>function countSubstring(s1, s2)
<syntaxhighlight lang="lua">function countSubstring(s1, s2)
local count = 0
local count = 0
for eachMatch in s1:gmatch(s2) do
for eachMatch in s1:gmatch(s2) do
Line 1,863: Line 1,863:


print(countSubstring("the three truths", "th"))
print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))</lang>
print(countSubstring("ababababab", "abab"))</syntaxhighlight>
<pre>3
<pre>3
2</pre>
2</pre>


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
f:=proc(s::string,c::string,count::nonnegint) local n;
f:=proc(s::string,c::string,count::nonnegint) local n;
n:=StringTools:-Search(c,s);
n:=StringTools:-Search(c,s);
Line 1,878: Line 1,878:


f("ababababab","abab",0);
f("ababababab","abab",0);
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,887: Line 1,887:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>StringPosition["the three truths","th",Overlaps->False]//Length
<syntaxhighlight lang="mathematica">StringPosition["the three truths","th",Overlaps->False]//Length
3
3
StringPosition["ababababab","abab",Overlaps->False]//Length
StringPosition["ababababab","abab",Overlaps->False]//Length
2</lang>
2</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==


<lang Matlab> % Count occurrences of a substring without overlap
<syntaxhighlight lang="matlab"> % Count occurrences of a substring without overlap
length(findstr("ababababab","abab",0))
length(findstr("ababababab","abab",0))
length(findstr("the three truths","th",0))
length(findstr("the three truths","th",0))


% Count occurrences of a substring with overlap
% Count occurrences of a substring with overlap
length(findstr("ababababab","abab",1)) </lang>
length(findstr("ababababab","abab",1)) </syntaxhighlight>


{{out}}
{{out}}
Line 1,914: Line 1,914:


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>scount(e, s) := block(
<syntaxhighlight lang="maxima">scount(e, s) := block(
[n: 0, k: 1],
[n: 0, k: 1],
while integerp(k: ssearch(e, s, k)) do (n: n + 1, k: k + 1),
while integerp(k: ssearch(e, s, k)) do (n: n + 1, k: k + 1),
Line 1,921: Line 1,921:


scount("na", "banana");
scount("na", "banana");
2</lang>
2</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>string.count = function(s)
<syntaxhighlight lang="miniscript">string.count = function(s)
return self.split(s).len - 1
return self.split(s).len - 1
end function
end function


print "the three truths".count("th")
print "the three truths".count("th")
print "ababababab".count("abab")</lang>
print "ababababab".count("abab")</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,937: Line 1,937:


=={{header|Mirah}}==
=={{header|Mirah}}==
<lang mirah>import java.util.regex.Pattern
<syntaxhighlight lang="mirah">import java.util.regex.Pattern
import java.util.regex.Matcher
import java.util.regex.Matcher


Line 1,975: Line 1,975:
puts count_substring3("abab", "ababababab") # ==> 2
puts count_substring3("abab", "ababababab") # ==> 2
puts count_substring3("a*b", "abaabba*bbaba*bbab") # ==> 2
puts count_substring3("a*b", "abaabba*bbaba*bbab") # ==> 2
</syntaxhighlight>
</lang>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Java}}
{{trans|Java}}
<lang Nanoquery>def countSubstring(str, subStr)
<syntaxhighlight lang="nanoquery">def countSubstring(str, subStr)
return int((len(str) - len(str.replace(subStr, ""))) / len(subStr))
return int((len(str) - len(str.replace(subStr, ""))) / len(subStr))
end</lang>
end</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
{{trans|F#}}
{{trans|F#}}
<lang Nemerle>using System.Console;
<syntaxhighlight lang="nemerle">using System.Console;


module CountSubStrings
module CountSubStrings
Line 2,007: Line 2,007:
WriteLine($"$target2 occurs $(text2.CountSubStrings(target2)) times in $text2");
WriteLine($"$target2 occurs $(text2.CountSubStrings(target2)) times in $text2");
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>th occurs 3 times in the three truths
<pre>th occurs 3 times in the three truths
Line 2,015: Line 2,015:
NetRexx provides the <tt>''string''.countstr(''needle'')</tt> built-in function:
NetRexx provides the <tt>''string''.countstr(''needle'')</tt> built-in function:


<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,037: Line 2,037:
return
return
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,046: Line 2,046:
=={{header|NewLISP}}==
=={{header|NewLISP}}==


<lang NewLISP>; file: stringcount.lsp
<syntaxhighlight lang="newlisp">; file: stringcount.lsp
; url: http://rosettacode.org/wiki/Count_occurrences_of_a_substring
; url: http://rosettacode.org/wiki/Count_occurrences_of_a_substring
; author: oofoe 2012-01-29
; author: oofoe 2012-01-29
Line 2,088: Line 2,088:
)
)


(exit)</lang>
(exit)</syntaxhighlight>


{{out}}
{{out}}
Line 2,101: Line 2,101:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import strutils
<syntaxhighlight lang="nim">import strutils


proc count(s, sub: string): int =
proc count(s, sub: string): int =
Line 2,114: Line 2,114:
echo count("the three truths","th")
echo count("the three truths","th")


echo count("ababababab","abab")</lang>
echo count("ababababab","abab")</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 2,121: Line 2,121:
=={{header|Objective-C}}==
=={{header|Objective-C}}==
The "split and count" method:
The "split and count" method:
<lang objc>@interface NSString (CountSubstrings)
<syntaxhighlight lang="objc">@interface NSString (CountSubstrings)
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
@end
@end
Line 2,140: Line 2,140:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 2,148: Line 2,148:


The "remove and count the difference" method:
The "remove and count the difference" method:
<lang objc>@interface NSString (CountSubstrings)
<syntaxhighlight lang="objc">@interface NSString (CountSubstrings)
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
@end
@end
Line 2,167: Line 2,167:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 2,175: Line 2,175:


Manual looping:
Manual looping:
<lang objc>@interface NSString (CountSubstrings)
<syntaxhighlight lang="objc">@interface NSString (CountSubstrings)
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
@end
@end
Line 2,200: Line 2,200:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 2,208: Line 2,208:
=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>let count_substring str sub =
<syntaxhighlight lang="ocaml">let count_substring str sub =
let sub_len = String.length sub in
let sub_len = String.length sub in
let len_diff = (String.length str) - sub_len
let len_diff = (String.length str) - sub_len
Line 2,224: Line 2,224:
Printf.printf "count 1: %d\n" (count_substring "the three truth" "th");
Printf.printf "count 1: %d\n" (count_substring "the three truth" "th");
Printf.printf "count 2: %d\n" (count_substring "ababababab" "abab");
Printf.printf "count 2: %d\n" (count_substring "ababababab" "abab");
;;</lang>
;;</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<syntaxhighlight lang="oforth">
<lang Oforth>
: countSubString(s, sub)
: countSubString(s, sub)
0 1 while(sub swap s indexOfAllFrom dup notNull) [ sub size + 1 under+ ]
0 1 while(sub swap s indexOfAllFrom dup notNull) [ sub size + 1 under+ ]
drop ;</lang>
drop ;</syntaxhighlight>


{{out}}
{{out}}
Line 2,242: Line 2,242:


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
bag="the three truths"
bag="the three truths"
x="th"
x="th"
Line 2,255: Line 2,255:
x="abab"
x="abab"
say left(bag,30) left(x,15) 'found' bag~caselesscountstr(x)
say left(bag,30) left(x,15) 'found' bag~caselesscountstr(x)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style="height:10ex;overflow:scroll">
<pre style="height:10ex;overflow:scroll">
Line 2,264: Line 2,264:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>subvec(v,u)={
<syntaxhighlight lang="parigp">subvec(v,u)={
my(i=1,s);
my(i=1,s);
while(i+#u<=#v,
while(i+#u<=#v,
Line 2,277: Line 2,277:
substr(s1,s2)=subvec(Vec(s1),Vec(s2));
substr(s1,s2)=subvec(Vec(s1),Vec(s2));
substr("the three truths","th")
substr("the three truths","th")
substr("ababababab","abab")</lang>
substr("ababababab","abab")</syntaxhighlight>
{{out}}
{{out}}
<pre>%1 = 3
<pre>%1 = 3
Line 2,286: Line 2,286:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>sub countSubstring {
<syntaxhighlight lang="perl">sub countSubstring {
my $str = shift;
my $str = shift;
my $sub = quotemeta(shift);
my $sub = quotemeta(shift);
Line 2,295: Line 2,295:
print countSubstring("the three truths","th"), "\n"; # prints "3"
print countSubstring("the three truths","th"), "\n"; # prints "3"
print countSubstring("ababababab","abab"), "\n"; # prints "2"</lang>
print countSubstring("ababababab","abab"), "\n"; # prints "2"</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #008000;">"the three truths"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"th"</span><span style="color: #0000FF;">},</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #008000;">"the three truths"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"th"</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #008000;">"ababababab"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"abab"</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #008000;">"ababababab"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"abab"</span><span style="color: #0000FF;">},</span>
Line 2,319: Line 2,319:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The string \"%s\" occurs as a non-overlapping substring %d times in \"%s\"\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">substring</span><span style="color: #0000FF;">,</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span><span style="color: #000000;">test</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The string \"%s\" occurs as a non-overlapping substring %d times in \"%s\"\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">substring</span><span style="color: #0000FF;">,</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span><span style="color: #000000;">test</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,331: Line 2,331:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
</syntaxhighlight>
</lang>


=={{header|Picat}}==
=={{header|Picat}}==
Line 2,342: Line 2,342:


===Recursion===
===Recursion===
<lang Picat>count_substrings_rec(S, SB) = C =>
<syntaxhighlight lang="picat">count_substrings_rec(S, SB) = C =>
count_rec(S,SB,0,C).
count_rec(S,SB,0,C).


Line 2,351: Line 2,351:
count_rec([T|Rest],SB,Count0,Count) :-
count_rec([T|Rest],SB,Count0,Count) :-
T != SB, % this character is not a substring
T != SB, % this character is not a substring
count_rec(Rest,SB,Count0,Count).</lang>
count_rec(Rest,SB,Count0,Count).</syntaxhighlight>


===Iterative===
===Iterative===
Iterative version using find/4 (wrap with once/1 to avoid backtracking).
Iterative version using find/4 (wrap with once/1 to avoid backtracking).
{{trans|Euphoria}}
{{trans|Euphoria}}
<lang Picat>count_substrings_find(S, SB) = C =>
<syntaxhighlight lang="picat">count_substrings_find(S, SB) = C =>
SLen = S.len,
SLen = S.len,
Count = 0,
Count = 0,
Line 2,369: Line 2,369:
)
)
end,
end,
C = Count.</lang>
C = Count.</syntaxhighlight>


The time differences between these two versions are quite large which is shown in a benchmark of searching the substring "ab" in a string of 100 000 random characters from the set of "abcde":
The time differences between these two versions are quite large which is shown in a benchmark of searching the substring "ab" in a string of 100 000 random characters from the set of "abcde":
Line 2,377: Line 2,377:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de countSubstring (Str Sub)
<syntaxhighlight lang="picolisp">(de countSubstring (Str Sub)
(let (Cnt 0 H (chop Sub))
(let (Cnt 0 H (chop Sub))
(for (S (chop Str) S (cdr S))
(for (S (chop Str) S (cdr S))
Line 2,383: Line 2,383:
(inc 'Cnt)
(inc 'Cnt)
(setq S (map prog2 H S)) ) )
(setq S (map prog2 H S)) ) )
Cnt ) )</lang>
Cnt ) )</syntaxhighlight>
Test:
Test:
<pre>: (countSubstring "the three truths" "th")
<pre>: (countSubstring "the three truths" "th")
Line 2,392: Line 2,392:


=={{header|Pike}}==
=={{header|Pike}}==
<syntaxhighlight lang="pike">
<lang Pike>
write("%d %d\n",
write("%d %d\n",
String.count("the three truths", "th"),
String.count("the three truths", "th"),
String.count("ababababab", "abab"));
String.count("ababababab", "abab"));
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,403: Line 2,403:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>cnt: procedure options (main);
<syntaxhighlight lang="pli">cnt: procedure options (main);
declare (i, tally) fixed binary;
declare (i, tally) fixed binary;
declare (text, key) character (100) varying;
declare (text, key) character (100) varying;
Line 2,416: Line 2,416:
end;
end;
put skip list (tally);
put skip list (tally);
end cnt;</lang>
end cnt;</syntaxhighlight>


Output for the two specified strings is as expected.
Output for the two specified strings is as expected.
Line 2,427: Line 2,427:


=={{header|PL/M}}==
=={{header|PL/M}}==
<lang plm>100H:
<syntaxhighlight lang="plm">100H:
/* CP/M CALLS */
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
Line 2,475: Line 2,475:


CALL EXIT;
CALL EXIT;
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 2,491: Line 2,491:
Note that while this example is marked as working with PB/Win, the <code>PRINT</code> statement would need to be replaced with <code>MSGBOX</code>, or output to a file. (PB/Win does not support console output.)
Note that while this example is marked as working with PB/Win, the <code>PRINT</code> statement would need to be replaced with <code>MSGBOX</code>, or output to a file. (PB/Win does not support console output.)


<lang powerbasic>FUNCTION PBMAIN () AS LONG
<syntaxhighlight lang="powerbasic">FUNCTION PBMAIN () AS LONG
PRINT "the three truths, th:", TALLY("the three truths", "th")
PRINT "the three truths, th:", TALLY("the three truths", "th")
PRINT "ababababab, abab:", TALLY("ababababab", "abab")
PRINT "ababababab, abab:", TALLY("ababababab", "abab")
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


{{out}}
{{out}}
Line 2,503: Line 2,503:


{{works with|PowerShell|4.0}}
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
[regex]::Matches("the three truths", "th").count
[regex]::Matches("the three truths", "th").count
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 2,511: Line 2,511:
</pre>
</pre>


<syntaxhighlight lang="powershell">
<lang PowerShell>
[regex]::Matches("ababababab","abab").count
[regex]::Matches("ababababab","abab").count
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 2,525: Line 2,525:
Using SWI-Prolog's string facilities (this solution is very similar to the Logtalk solution that uses sub_atom/5):
Using SWI-Prolog's string facilities (this solution is very similar to the Logtalk solution that uses sub_atom/5):


<lang prolog>
<syntaxhighlight lang="prolog">


count_substring(String, Sub, Total) :-
count_substring(String, Sub, Total) :-
Line 2,543: Line 2,543:
DropN is Before + Length,
DropN is Before + Length,
sub_string(String, DropN, Remain, 0, Rest).
sub_string(String, DropN, Remain, 0, Rest).
</syntaxhighlight>
</lang>


Usage:
Usage:
<lang prolog>
<syntaxhighlight lang="prolog">
?- count_substring("the three truths","th",X).
?- count_substring("the three truths","th",X).
X = 3.
X = 3.
Line 2,552: Line 2,552:
?- count_substring("ababababab","abab",X).
?- count_substring("ababababab","abab",X).
X = 2.
X = 2.
</syntaxhighlight>
</lang>


=== version using DCG ===
=== version using DCG ===


{{works with|SWI-Prolog|7.6.4}}
{{works with|SWI-Prolog|7.6.4}}
<lang prolog>
<syntaxhighlight lang="prolog">
:- system:set_prolog_flag(double_quotes,chars) .
:- system:set_prolog_flag(double_quotes,chars) .


Line 2,591: Line 2,591:
.
.


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,614: Line 2,614:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>a = CountString("the three truths","th")
<syntaxhighlight lang="purebasic">a = CountString("the three truths","th")
b = CountString("ababababab","abab")
b = CountString("ababababab","abab")
; a = 3
; a = 3
; b = 2</lang>
; b = 2</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>>>> "the three truths".count("th")
<syntaxhighlight lang="python">>>> "the three truths".count("th")
3
3
>>> "ababababab".count("abab")
>>> "ababababab".count("abab")
2</lang>
2</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==
Line 2,629: Line 2,629:
Quackery does not come equipped with a "find substring m within string n" function, but one is defined in The Book of Quackery, as a demonstration of creating a finite state machine in Quackery. It is reproduced here with permission.
Quackery does not come equipped with a "find substring m within string n" function, but one is defined in The Book of Quackery, as a demonstration of creating a finite state machine in Quackery. It is reproduced here with permission.


<lang Quackery> [ [] 95 times
<syntaxhighlight lang="quackery"> [ [] 95 times
[ i^ space +
[ i^ space +
join ] ] constant is alphabet ( --> $ )
join ] ] constant is alphabet ( --> $ )
Line 2,683: Line 2,683:
else
else
[ swap buildfsm
[ swap buildfsm
usefsm ] ] is find$ ( $ $ --> n )</lang>
usefsm ] ] is find$ ( $ $ --> n )</syntaxhighlight>


<code>find$</code> builds a finite state machine to search for m, (an O(m³) operation), then uses it to search in n with O(n). Rather than use <code>find$</code>, and repeatedly build the same fsm, we will define a word <code>findall$</code> which returns a nest (i.e. list) of positions of m within n. (It actually returns the positions of the end of the substring, relative to (for the first instance) the start of the string, or (for subsequent instances) the end of the previous instance of the substring.)
<code>find$</code> builds a finite state machine to search for m, (an O(m³) operation), then uses it to search in n with O(n). Rather than use <code>find$</code>, and repeatedly build the same fsm, we will define a word <code>findall$</code> which returns a nest (i.e. list) of positions of m within n. (It actually returns the positions of the end of the substring, relative to (for the first instance) the start of the string, or (for subsequent instances) the end of the previous instance of the substring.)


<lang Quackery> [ over size 0 = iff
<syntaxhighlight lang="quackery"> [ over size 0 = iff
[ 2drop [] ] done
[ 2drop [] ] done
[] unrot
[] unrot
Line 2,700: Line 2,700:
nip swap again ]
nip swap again ]
2drop drop ] is findall$ ( $ $ --> [ )
2drop drop ] is findall$ ( $ $ --> [ )
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,719: Line 2,719:
Finally we can use <code>findall$</code> to fulfil the task requirements.
Finally we can use <code>findall$</code> to fulfil the task requirements.


<lang Quackery> [ swap findall$ size ] is occurences ( $ $ --> n )
<syntaxhighlight lang="quackery"> [ swap findall$ size ] is occurences ( $ $ --> n )


$ "the three truths" $ "th" occurences echo cr
$ "the three truths" $ "th" occurences echo cr
$ "ababababab" $ "abab" occurences echo cr
$ "ababababab" $ "abab" occurences echo cr
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,735: Line 2,735:
The <code>fixed</code> parameter (and, in <code>stringr</code>, the function of the same name) is used to specify a search for a fixed string. Otherwise, the search pattern is interpreted as a POSIX regular expression. PCRE is also an option: use the <code>perl</code> parameter or function.
The <code>fixed</code> parameter (and, in <code>stringr</code>, the function of the same name) is used to specify a search for a fixed string. Otherwise, the search pattern is interpreted as a POSIX regular expression. PCRE is also an option: use the <code>perl</code> parameter or function.


<lang rsplus>count = function(haystack, needle)
<syntaxhighlight lang="rsplus">count = function(haystack, needle)
{v = attr(gregexpr(needle, haystack, fixed = T)[[1]], "match.length")
{v = attr(gregexpr(needle, haystack, fixed = T)[[1]], "match.length")
if (identical(v, -1L)) 0 else length(v)}
if (identical(v, -1L)) 0 else length(v)}


print(count("hello", "l"))</lang>
print(count("hello", "l"))</syntaxhighlight>


{{libheader|stringr}}
{{libheader|stringr}}


<lang rsplus>library(stringr)
<syntaxhighlight lang="rsplus">library(stringr)
print(str_count("hello", fixed("l")))</lang>
print(str_count("hello", fixed("l")))</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
(define count-substring
(define count-substring
(compose length regexp-match*))
(compose length regexp-match*))
</syntaxhighlight>
</lang>
<lang racket>
<syntaxhighlight lang="racket">
> (count-substring "th" "the three truths")
> (count-substring "th" "the three truths")
3
3
> (count-substring "abab" "ababababab")
> (count-substring "abab" "ababababab")
2
2
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>sub count-substring($big, $little) { +$big.comb: / :r $little / }
<syntaxhighlight lang="raku" line>sub count-substring($big, $little) { +$big.comb: / :r $little / }
say count-substring("the three truths", "th"); # 3
say count-substring("the three truths", "th"); # 3
say count-substring("ababababab", "abab"); # 2
say count-substring("ababababab", "abab"); # 2
say count-substring(123123123, 12); # 3</lang>
say count-substring(123123123, 12); # 3</syntaxhighlight>
The <tt>:r</tt> adverb makes the regex "ratchet forward" and skip any overlapping matches. <tt>.comb</tt> - when given a <tt>Regex</tt> as an argument - returns instances of that substring. Also, prefix <tt>+</tt> forces numeric context in Raku (it's a no-op in Perl&nbsp;5). For the built in listy types that is the same as calling <tt>.elems</tt> method. One other style point: we now tend to prefer hyphenated names over camelCase.
The <tt>:r</tt> adverb makes the regex "ratchet forward" and skip any overlapping matches. <tt>.comb</tt> - when given a <tt>Regex</tt> as an argument - returns instances of that substring. Also, prefix <tt>+</tt> forces numeric context in Raku (it's a no-op in Perl&nbsp;5). For the built in listy types that is the same as calling <tt>.elems</tt> method. One other style point: we now tend to prefer hyphenated names over camelCase.


=={{header|Red}}==
=={{header|Red}}==
<lang Red>Red []
<syntaxhighlight lang="red">Red []


count-occurrences: function [string substring] [
count-occurrences: function [string substring] [
Line 2,780: Line 2,780:
print [test-case-1 "-" count-occurrences test-case-1 "th"]
print [test-case-1 "-" count-occurrences test-case-1 "th"]
print [test-case-2 "-" count-occurrences test-case-2 "abab"]
print [test-case-2 "-" count-occurrences test-case-2 "abab"]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>the three truths - 3
<pre>the three truths - 3
Line 2,802: Line 2,802:
::::* &nbsp; too many arguments
::::* &nbsp; too many arguments
::::* &nbsp; if &nbsp; '''start''' &nbsp; is a positive integer (when specified)
::::* &nbsp; if &nbsp; '''start''' &nbsp; is a positive integer (when specified)
<lang rexx>/*REXX program counts the occurrences of a (non─overlapping) substring in a string. */
<syntaxhighlight lang="rexx">/*REXX program counts the occurrences of a (non─overlapping) substring in a string. */
w=. /*max. width so far.*/
w=. /*max. width so far.*/
bag= 'the three truths' ; x= "th" ; call showResult
bag= 'the three truths' ; x= "th" ; call showResult
Line 2,830: Line 2,830:
if x=='' then x= " (null)" /* " " " " */
if x=='' then x= " (null)" /* " " " " */
say left(bag, w) left(x, w%2) center(countstr(bag, x), 5)
say left(bag, w) left(x, w%2) center(countstr(bag, x), 5)
return</lang>
return</syntaxhighlight>
'''output''' &nbsp; when using the default (internal) inputs:
'''output''' &nbsp; when using the default (internal) inputs:
<pre>
<pre>
Line 2,847: Line 2,847:


=={{header|Ring}}==
=={{header|Ring}}==
<syntaxhighlight lang="ring">
<lang Ring>
aString = "Ring Welcome Ring to the Ring Ring Programming Ring Language Ring"
aString = "Ring Welcome Ring to the Ring Ring Programming Ring Language Ring"
bString = "Ring"
bString = "Ring"
Line 2,858: Line 2,858:
cString = substr(cString,substr(cString,dString)+len(string(sum)))
cString = substr(cString,substr(cString,dString)+len(string(sum)))
end
end
return sum</lang>
return sum</syntaxhighlight>


Output:
Output:
Line 2,866: Line 2,866:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def countSubstrings str, subStr
<syntaxhighlight lang="ruby">def countSubstrings str, subStr
str.scan(subStr).length
str.scan(subStr).length
end
end


p countSubstrings "the three truths", "th" #=> 3
p countSubstrings "the three truths", "th" #=> 3
p countSubstrings "ababababab", "abab" #=> 2</lang>
p countSubstrings "ababababab", "abab" #=> 2</syntaxhighlight>


String#scan returns an array of substrings, and Array#length (or Array#size) counts them.
String#scan returns an array of substrings, and Array#length (or Array#size) counts them.


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>print countSubstring("the three truths","th")
<syntaxhighlight lang="runbasic">print countSubstring("the three truths","th")
print countSubstring("ababababab","abab")
print countSubstring("ababababab","abab")


Line 2,884: Line 2,884:
i = instr(s$,find$,i) + len(find$)
i = instr(s$,find$,i) + len(find$)
WEND
WEND
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 2,890: Line 2,890:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>
<syntaxhighlight lang="rust">
fn main() {
fn main() {
println!("{}","the three truths".matches("th").count());
println!("{}","the three truths".matches("th").count());
println!("{}","ababababab".matches("abab").count());
println!("{}","ababababab".matches("abab").count());
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,904: Line 2,904:
=={{header|Scala}}==
=={{header|Scala}}==
===Using Recursion===
===Using Recursion===
<lang scala>import scala.annotation.tailrec
<syntaxhighlight lang="scala">import scala.annotation.tailrec
def countSubstring(str1:String, str2:String):Int={
def countSubstring(str1:String, str2:String):Int={
@tailrec def count(pos:Int, c:Int):Int={
@tailrec def count(pos:Int, c:Int):Int={
Line 2,911: Line 2,911:
}
}
count(0,0)
count(0,0)
}</lang>
}</syntaxhighlight>


===Using Sliding===
===Using Sliding===
<lang scala>def countSubstring(str: String, sub: String): Int =
<syntaxhighlight lang="scala">def countSubstring(str: String, sub: String): Int =
str.sliding(sub.length).count(_ == sub)</lang><br/>
str.sliding(sub.length).count(_ == sub)</syntaxhighlight><br/>


===Using Regular Expressions===
===Using Regular Expressions===
<lang scala>def countSubstring( str:String, substr:String ) = substr.r.findAllMatchIn(str).length</lang>
<syntaxhighlight lang="scala">def countSubstring( str:String, substr:String ) = substr.r.findAllMatchIn(str).length</syntaxhighlight>
<br/>
<br/>
<lang scala>println(countSubstring("ababababab", "abab"))
<syntaxhighlight lang="scala">println(countSubstring("ababababab", "abab"))
println(countSubstring("the three truths", "th"))</lang>
println(countSubstring("the three truths", "th"))</syntaxhighlight>
{{out}}
{{out}}
<pre>2
<pre>2
Line 2,928: Line 2,928:
=={{header|Scheme}}==
=={{header|Scheme}}==
{{works with|Gauche Scheme}}
{{works with|Gauche Scheme}}
<lang Scheme>gosh> (use gauche.lazy)
<syntaxhighlight lang="scheme">gosh> (use gauche.lazy)
#<undef>
#<undef>
gosh> (length (lrxmatch "th" "the three truths"))
gosh> (length (lrxmatch "th" "the three truths"))
Line 2,934: Line 2,934:
gosh> (length (lrxmatch "abab" "ababababab"))
gosh> (length (lrxmatch "abab" "ababababab"))
2
2
</syntaxhighlight>
</lang>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const func integer: countSubstring (in string: stri, in string: searched) is func
const func integer: countSubstring (in string: stri, in string: searched) is func
Line 2,956: Line 2,956:
writeln(countSubstring("the three truths", "th"));
writeln(countSubstring("the three truths", "th"));
writeln(countSubstring("ababababab", "abab"));
writeln(countSubstring("ababababab", "abab"));
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 2,966: Line 2,966:
=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
'''Simply stated:'''
'''Simply stated:'''
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
put the number of occurrences of "th" in "the three truths" --> 3
put the number of occurrences of "th" in "the three truths" --> 3
put the number of occurrences of "abab" in "ababababab" -- > 2
put the number of occurrences of "abab" in "ababababab" -- > 2
</syntaxhighlight>
</lang>
'''User-created function:'''
'''User-created function:'''
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
put countSubstring("aaaaa","a") // 5
put countSubstring("aaaaa","a") // 5
put countSubstring("abababa","aba") // 2
put countSubstring("abababa","aba") // 2
Line 2,978: Line 2,978:
return number of occurrences of subString in mainString
return number of occurrences of subString in mainString
end countSubstring
end countSubstring
</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
'''Built-in:'''
'''Built-in:'''
<lang ruby>say "the three truths".count("th");
<syntaxhighlight lang="ruby">say "the three truths".count("th");
say "ababababab".count("abab");</lang>
say "ababababab".count("abab");</syntaxhighlight>


'''User-created function:'''
'''User-created function:'''
<lang ruby>func countSubstring(s, ss) {
<syntaxhighlight lang="ruby">func countSubstring(s, ss) {
var re = Regex.new(ss.escape, 'g'); # 'g' for global
var re = Regex.new(ss.escape, 'g'); # 'g' for global
var counter = 0;
var counter = 0;
Line 2,994: Line 2,994:


say countSubstring("the three truths","th");
say countSubstring("the three truths","th");
say countSubstring("ababababab","abab");</lang>
say countSubstring("ababababab","abab");</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,001: Line 3,001:
</pre>
</pre>
=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>BEGIN
<syntaxhighlight lang="simula">BEGIN
INTEGER PROCEDURE COUNTSUBSTRING(T,TSUB); TEXT T,TSUB;
INTEGER PROCEDURE COUNTSUBSTRING(T,TSUB); TEXT T,TSUB;
Line 3,020: Line 3,020:
OUTINT(COUNTSUBSTRING("ABABABABAB", "ABAB"),0);
OUTINT(COUNTSUBSTRING("ABABABABAB", "ABAB"),0);
OUTIMAGE;
OUTIMAGE;
END.</lang>
END.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,029: Line 3,029:
=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
<lang smalltalk>Transcript showCR:('the three truths' occurrencesOfString:'th').
<syntaxhighlight lang="smalltalk">Transcript showCR:('the three truths' occurrencesOfString:'th').
Transcript showCR:('ababababab' occurrencesOfString:'abab')</lang>
Transcript showCR:('ababababab' occurrencesOfString:'abab')</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 3,036: Line 3,036:


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<syntaxhighlight lang="snobol4">
<lang SNOBOL4>
DEFINE("countSubstring(t,s)")
DEFINE("countSubstring(t,s)")


Line 3,048: Line 3,048:
3
3
2
2
</syntaxhighlight>
</lang>


=={{header|Standard ML}}==
=={{header|Standard ML}}==


<lang sml>fun count_substrings (str, sub) =
<syntaxhighlight lang="sml">fun count_substrings (str, sub) =
let
let
fun aux (str', count) =
fun aux (str', count) =
Line 3,069: Line 3,069:
print (Int.toString (count_substrings ("the three truths", "th")) ^ "\n");
print (Int.toString (count_substrings ("the three truths", "th")) ^ "\n");
print (Int.toString (count_substrings ("ababababab", "abab")) ^ "\n");
print (Int.toString (count_substrings ("ababababab", "abab")) ^ "\n");
print (Int.toString (count_substrings ("abaabba*bbaba*bbab", "a*b")) ^ "\n");</lang>
print (Int.toString (count_substrings ("abaabba*bbaba*bbab", "a*b")) ^ "\n");</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>function strcount(s, x) {
<syntaxhighlight lang="stata">function strcount(s, x) {
n = 0
n = 0
k = 1-(i=strlen(x))
k = 1-(i=strlen(x))
Line 3,085: Line 3,085:


strcount("ababababab","abab")
strcount("ababababab","abab")
2</lang>
2</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


func countSubstring(str: String, substring: String) -> Int {
func countSubstring(str: String, substring: String) -> Int {
Line 3,096: Line 3,096:


print(countSubstring(str: "the three truths", substring: "th"))
print(countSubstring(str: "the three truths", substring: "th"))
print(countSubstring(str: "ababababab", substring: "abab"))</lang>
print(countSubstring(str: "ababababab", substring: "abab"))</syntaxhighlight>


{{out}}
{{out}}
Line 3,105: Line 3,105:
=={{header|Tcl}}==
=={{header|Tcl}}==
The regular expression engine is ideal for this task, especially as the <tt>***=</tt> prefix makes it interpret the rest of the argument as a literal string to match:
The regular expression engine is ideal for this task, especially as the <tt>***=</tt> prefix makes it interpret the rest of the argument as a literal string to match:
<lang tcl>proc countSubstrings {haystack needle} {
<syntaxhighlight lang="tcl">proc countSubstrings {haystack needle} {
regexp -all ***=$needle $haystack
regexp -all ***=$needle $haystack
}
}
puts [countSubstrings "the three truths" "th"]
puts [countSubstrings "the three truths" "th"]
puts [countSubstrings "ababababab" "abab"]
puts [countSubstrings "ababababab" "abab"]
puts [countSubstrings "abaabba*bbaba*bbab" "a*b"]</lang>
puts [countSubstrings "abaabba*bbaba*bbab" "a*b"]</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 3,117: Line 3,117:


=={{header|Transd}}==
=={{header|Transd}}==
<lang scheme>#lang transd
<syntaxhighlight lang="scheme">#lang transd


MainModule: {
MainModule: {
Line 3,130: Line 3,130:
(countSubstring "ababababab" "abab")
(countSubstring "ababababab" "abab")
)
)
}</lang>{{out}}
}</syntaxhighlight>{{out}}
<pre>
<pre>
3
3
Line 3,137: Line 3,137:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT, {}
$$ MODE TUSCRIPT, {}
occurences=COUNT ("the three truths", ":th:")
occurences=COUNT ("the three truths", ":th:")
occurences=COUNT ("ababababab", ":abab:")
occurences=COUNT ("ababababab", ":abab:")
occurences=COUNT ("abaabba*bbaba*bbab",":a\*b:")
occurences=COUNT ("abaabba*bbaba*bbab",":a\*b:")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,152: Line 3,152:
=={{header|TXR}}==
=={{header|TXR}}==


<lang txr>@(next :args)
<syntaxhighlight lang="txr">@(next :args)
@(do (defun count-occurrences (haystack needle)
@(do (defun count-occurrences (haystack needle)
(for* ((occurrences 0)
(for* ((occurrences 0)
Line 3,165: Line 3,165:
@(output)
@(output)
@(count-occurrences hay ndl) occurrences(s) of @ndl inside @hay
@(count-occurrences hay ndl) occurrences(s) of @ndl inside @hay
@(end)</lang>
@(end)</syntaxhighlight>


<pre>$ ./txr count-occurrences.txr "baba" "babababa"
<pre>$ ./txr count-occurrences.txr "baba" "babababa"
Line 3,174: Line 3,174:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bash}}
{{works with|Bash}}
<lang bash>#!/bin/bash
<syntaxhighlight lang="bash">#!/bin/bash


function countString(){
function countString(){
Line 3,188: Line 3,188:


countString "the three truths" "th"
countString "the three truths" "th"
countString "ababababab" "abab"</lang>
countString "ababababab" "abab"</syntaxhighlight>
{{Out}}
{{Out}}
<pre>3
<pre>3
Line 3,195: Line 3,195:
=={{header|VBA}}==
=={{header|VBA}}==


<lang VBA>Function CountStringInString(stLookIn As String, stLookFor As String)
<syntaxhighlight lang="vba">Function CountStringInString(stLookIn As String, stLookFor As String)
CountStringInString = UBound(Split(stLookIn, stLookFor))
CountStringInString = UBound(Split(stLookIn, stLookFor))
End Function</lang>
End Function</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
'''user created function'''
'''user created function'''
<syntaxhighlight lang="vb">
<lang vb>
Function CountSubstring(str,substr)
Function CountSubstring(str,substr)
CountSubstring = 0
CountSubstring = 0
Line 3,218: Line 3,218:
WScript.StdOut.Write CountSubstring("the three truths","th") & vbCrLf
WScript.StdOut.Write CountSubstring("the three truths","th") & vbCrLf
WScript.StdOut.Write CountSubstring("ababababab","abab") & vbCrLf
WScript.StdOut.Write CountSubstring("ababababab","abab") & vbCrLf
</syntaxhighlight>
</lang>
'''Using built-in Regexp'''
'''Using built-in Regexp'''


Run it with CScript.
Run it with CScript.
<syntaxhighlight lang="vb">
<lang vb>
function CountSubstring(str,substr)
function CountSubstring(str,substr)
with new regexp
with new regexp
Line 3,233: Line 3,233:
WScript.StdOut.Writeline CountSubstring("the three truths","th")
WScript.StdOut.Writeline CountSubstring("the three truths","th")
WScript.StdOut.Writeline CountSubstring("ababababab","abab")
WScript.StdOut.Writeline CountSubstring("ababababab","abab")
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,241: Line 3,241:


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vbnet>Module Count_Occurrences_of_a_Substring
<syntaxhighlight lang="vbnet">Module Count_Occurrences_of_a_Substring
Sub Main()
Sub Main()
Console.WriteLine(CountSubstring("the three truths", "th"))
Console.WriteLine(CountSubstring("the three truths", "th"))
Line 3,260: Line 3,260:
Return count
Return count
End Function
End Function
End Module</lang>
End Module</syntaxhighlight>
{{Out}}
{{Out}}
<pre>3
<pre>3
Line 3,268: Line 3,268:


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>fn main(){
<syntaxhighlight lang="vlang">fn main(){
println('the three truths'.count('th'))
println('the three truths'.count('th'))
println('ababababab'.count('abab'))
println('ababababab'.count('abab'))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,280: Line 3,280:


=={{header|Wortel}}==
=={{header|Wortel}}==
<lang wortel>@let {
<syntaxhighlight lang="wortel">@let {
c &[s t] #!s.match &(t)g
c &[s t] #!s.match &(t)g


Line 3,287: Line 3,287:
!!c "ababababab" "abab"
!!c "ababababab" "abab"
]]
]]
}</lang>
}</syntaxhighlight>
Returns: <pre>[3 2]</pre>
Returns: <pre>[3 2]</pre>


Line 3,293: Line 3,293:
{{libheader|Wren-pattern}}
{{libheader|Wren-pattern}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/pattern" for Pattern
<syntaxhighlight lang="ecmascript">import "/pattern" for Pattern
import "/fmt" for Fmt
import "/fmt" for Fmt


Line 3,312: Line 3,312:
var count = countSubstring.call(test[0], test[1])
var count = countSubstring.call(test[0], test[1])
Fmt.print("$6s occurs $d times in $q.", Fmt.q(test[1]), count, test[0])
Fmt.print("$6s occurs $d times in $q.", Fmt.q(test[1]), count, test[0])
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,324: Line 3,324:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings, instead of MSb terminated
string 0; \use zero-terminated strings, instead of MSb terminated


Line 3,364: Line 3,364:
[IntOut(0, SubStr("the three truths", "th")); CrLf(0);
[IntOut(0, SubStr("the three truths", "th")); CrLf(0);
IntOut(0, SubStr("ababababab", "abab")); CrLf(0);
IntOut(0, SubStr("ababababab", "abab")); CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 3,385: Line 3,385:
=={{header|zkl}}==
=={{header|zkl}}==
Two solutions:
Two solutions:
<lang zkl>fcn countSubstring(s,p){ pn:=p.len(); cnt:=n:=0;
<syntaxhighlight lang="zkl">fcn countSubstring(s,p){ pn:=p.len(); cnt:=n:=0;
while(Void!=(n:=s.find(p,n))){cnt+=1; n+=pn}
while(Void!=(n:=s.find(p,n))){cnt+=1; n+=pn}
cnt
cnt
}</lang>
}</syntaxhighlight>
{{trans|J}}
{{trans|J}}
<lang zkl>fcn countSubstring(s,p){ (pl:=p.len()) and (s.len()-(s-p).len())/pl }</lang>
<syntaxhighlight lang="zkl">fcn countSubstring(s,p){ (pl:=p.len()) and (s.len()-(s-p).len())/pl }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,402: Line 3,402:


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>10 LET t$="ABABABABAB": LET p$="ABAB": GO SUB 1000
<syntaxhighlight lang="zxbasic">10 LET t$="ABABABABAB": LET p$="ABAB": GO SUB 1000
20 LET t$="THE THREE TRUTHS": LET p$="TH": GO SUB 1000
20 LET t$="THE THREE TRUTHS": LET p$="TH": GO SUB 1000
30 STOP
30 STOP
Line 3,411: Line 3,411:
1040 NEXT i
1040 NEXT i
1050 PRINT p$;"=";c''
1050 PRINT p$;"=";c''
1060 RETURN </lang>
1060 RETURN </syntaxhighlight>