Count occurrences of a substring: Difference between revisions

m
no edit summary
(Added Quackery.)
mNo edit summary
 
(48 intermediate revisions by 25 users not shown)
Line 10:
 
It should return an integer count.
<langsyntaxhighlight lang="pseudocode">print countSubstring("the three truths","th")
3
 
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2</langsyntaxhighlight>
 
The matching should yield the highest number of non-overlapping matches.
Line 26:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">print(‘the three truths’.count(‘th’))
print(‘ababababab’.count(‘abab’))</langsyntaxhighlight>
 
{{out}}
Line 37:
=={{header|360 Assembly}}==
The program uses two ASSIST macros (XDECO,XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Count occurrences of a substring 05/07/2016
COUNTSTR CSECT
USING COUNTSTR,R13 base register
Line 102:
* ---- -------------------------------------------------------
YREGS
END COUNTSTR</langsyntaxhighlight>
{{out}}
<pre>
Line 115:
<code>DE</code>.
 
<langsyntaxhighlight lang="8080asm"> org 100h
jmp demo
;;; Count non-overlapping substrings (BC) in string (HL)
Line 170:
sub2: db 'abab',0 ; result should be 2
str3: db 'cat',0
sub3: db 'dog',0 ; result should be 0</langsyntaxhighlight>
 
{{out}}
Line 177:
 
=={{header|8086 Assembly}}==
<langsyntaxhighlight lang="asm"> cpu 8086
org 100h
section .text
Line 242:
.sub2: db 'abab',0 ; result should be 2
.str3: db 'cat',0
.sub3: db 'dog',0 ; result should be 0</langsyntaxhighlight>
 
{{out}}
 
<pre>3 2 0</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program strcptsub64.s */
 
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
/************************************/
/* Initialized data */
/************************************/
.data
szMessResult: .asciz "Result: "
szString: .asciz "the three truths"
szSubString: .asciz "th"
szString1: .asciz "ababababab"
szSubString1: .asciz "abab"
szCarriageReturn: .asciz "\n"
szMessStart: .asciz "Program 64 bits start.\n"
/************************************/
/* UnInitialized data */
/************************************/
.bss
sZoneConv: .skip 24
/************************************/
/* code section */
/************************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess
ldr x0,qAdrszString
ldr x1,qAdrszSubString
bl countSubString
ldr x0,qAdrszString1
ldr x1,qAdrszSubString1
bl countSubString
 
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
qAdrszString: .quad szString
qAdrszSubString: .quad szSubString
qAdrszString1: .quad szString1
qAdrszSubString1: .quad szSubString1
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessStart: .quad szMessStart
/***************************************************/
/* count sub string of string */
/***************************************************/
/* r0 contains a string */
/* r1 contains a substring */
/* r0 return substring count */
countSubString:
stp x1,lr,[sp,-16]!
stp x2,x3,[sp,-16]!
stp x4,x5,[sp,-16]!
stp x6,x7,[sp,-16]!
mov x4,#0 // counter
mov x3,#0 // index string
mov x5,#0 // index substring
1:
ldrb w6,[x0,x5] // load byte of string
ldrb w7,[x1,x3] // load byte of substring
cmp x6,x7 // compare byte
bne 2f // not equal
cmp x6,#0 // string end ?
beq 3f // yes
add x5,x5,#1 // else increment index
add x3,x3,#1
b 1b // and loop
2: // characters not equal
cmp x6,#0 // end string ?
beq 4f
cmp x7,#0 // end substring ?
add x6,x4,1
csel x4,x6,x4,eq // yes -> increment counter
mov x3,#0 // raz index substring
add x5,x5,#1 // increment string index
b 1b // and loop
3: // end string and end substring
add x4,x4,#1 // increment counter
4: // result display
mov x0,x4
ldr x1,qAdrsZoneConv
bl conversion10
ldr x0,qAdrszMessResult
bl affichageMess
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
mov x0,x4
100:
ldp x6,x7,[sp],16
ldp x4,x5,[sp],16
ldp x2,x3,[sp],16
ldp x1,lr,[sp],16
ret
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
 
</syntaxhighlight>
{{Out}}
<pre>
Program 64 bits start.
Result: 3
Result: 2
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC CountSubstring(CHAR ARRAY s,sub)
BYTE i,j,res,found
 
i=1 res=0
WHILE i-1+sub(0)<=s(0)
DO
found=1
FOR j=1 TO sub(0)
DO
IF s(j+i-1)#sub(j) THEN
found=0
EXIT
FI
OD
 
IF found=1 THEN
i==+sub(0)
res==+1
ELSE
i==+1
FI
OD
RETURN (res)
 
PROC Test(CHAR ARRAY s,sub)
BYTE c
 
c=CountSubstring(s,sub)
PrintF("%B ""%S"" in ""%S""%E",c,sub,s)
RETURN
 
PROC Main()
Test("the three truths","th")
Test("ababababab","abab")
Test("11111111","11")
Test("abcdefg","123")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Count_occurrences_of_a_substring.png Screenshot from Atari 8-bit computer]
<pre>
3 "th" in "the three truths"
2 "abab" in "ababababab"
4 "11" in "11111111"
0 "123" in "abcdefg"
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Strings.Fixed, Ada.Integer_Text_IO;
 
procedure Substrings is
Line 257 ⟶ 424:
Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => "ababababab",
Pattern => "abab"));
end Substrings;</langsyntaxhighlight>
 
{{out}}
Line 263 ⟶ 430:
 
=={{header|ALGOL 68}}==
Algol68 has no build in function to do this task, hence the need to create a ''count string in string'' routine.<br/>
{{works with|ALGOL 68|Revision 1 - no extensions to language used.}}
If your Algol 68 compiler/interpreter does not have ''string in string'', there is an implementation on Rosetta Code [[ALGOL_68/prelude#string_in_string|here]].<br>
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
<syntaxhighlight lang="algol68">PROC count string in string = (STRING needle, haystack)INT: (
{{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.
<lang algol68>#!/usr/local/bin/a68g --script #
 
PROC count string in string = (STRING needle, haystack)INT: (
INT start:=LWB haystack, next, out:=0;
FOR count WHILE string in string(needle, next, haystack[start:]) DO
Line 278 ⟶ 441:
);
 
print((
printf(($d" "$,
whole( count string in string("th", "the three truths"), 0 ) # expect 3 #, " ",
whole( count string in string("abab", "ababababab"), 0 ) # expect 2 #, " ",
whole( count string in string("a*b", "abaabba*bbaba*bbab"), 0 ) # expect 2 #, newline
))
$l$
</syntaxhighlight>
))</lang>
{{out}}
 
<pre>
3 2 2
Line 291 ⟶ 454:
=={{header|Apex}}==
Apex example for 'Count occurrences of a substring'.
<syntaxhighlight lang="apex">
<lang Apex>
String substr = 'ABC';
String str = 'ABCZZZABCYABCABCXXABC';
Line 303 ⟶ 466:
}
System.debug('Count String : '+count);
</syntaxhighlight>
</lang>
 
<pre>
Line 312 ⟶ 475:
{{works with|Dyalog APL}}
 
<langsyntaxhighlight lang="apl">csubs←{0=x←⊃⍸⍺⍷⍵:0 ⋄ 1+⍺∇(¯1+x+⍴⍺)↓⍵}</langsyntaxhighlight>
 
{{out}}
Line 320 ⟶ 483:
 
=={{header|AppleScript}}==
 
This is a good example of the kind of problem to which standard libraries (a regex library in this case) would offer most languages a simple and immediate solution.
AppleScript, however, for want of various basics like regex and math library functions, can require scripters to draw on the supplementary resources of Bash, using the built-in ''do shell script'' function.
Line 328 ⟶ 490:
Here we use a generic ''evalOSA(language, code)'' function to apply a JavaScript for Automation regex to a pair of AppleScript strings, using OSAKit.
 
<langsyntaxhighlight AppleScriptlang="applescript">use framework "OSAKit"
 
on run
Line 356 ⟶ 518:
return oError's NSLocalizedDescription as text
end evalOSA</langsyntaxhighlight>
 
{{out}}
Line 365 ⟶ 527:
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.
 
<langsyntaxhighlight lang="applescript">on countSubstring(theString, theSubstring)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to theSubstring
Line 374 ⟶ 536:
end countSubstring
 
{countSubstring("the three truths", "th"), countSubstring("ababababab", "abab")}</langsyntaxhighlight>
 
{{Out}}
<syntaxhighlight lang ="applescript">{3, 2}</langsyntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program strcptsub.s */
 
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../constantes.inc"
 
/************************************/
/* Initialized data */
/************************************/
.data
szMessResult: .asciz "Result: "
szString: .asciz "the three truths"
szSubString: .asciz "th"
szString1: .asciz "ababababab"
szSubString1: .asciz "abab"
szCarriageReturn: .asciz "\n"
szMessStart: .asciz "Program 32 bits start.\n"
/************************************/
/* UnInitialized data */
/************************************/
.bss
sZoneConv: .skip 24
/************************************/
/* code section */
/************************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessStart
bl affichageMess
ldr r0,iAdrszString
ldr r1,iAdrszSubString
bl countSubString
ldr r0,iAdrszString1
ldr r1,iAdrszSubString1
bl countSubString
 
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform the system call
iAdrszString: .int szString
iAdrszSubString: .int szSubString
iAdrszString1: .int szString1
iAdrszSubString1: .int szSubString1
iAdrsZoneConv: .int sZoneConv
iAdrszMessResult: .int szMessResult
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessStart: .int szMessStart
/***************************************************/
/* count sub string of string */
/***************************************************/
/* r0 contains a string */
/* r1 contains a substring */
/* r0 return substring count */
countSubString:
push {r1-r7,lr} @ save registers
mov r4,#0 @ counter
mov r3,#0 @ index string
Mov r5,#0 @ index substring
1:
ldrb r6,[r0,r5] @ load byte of string
ldrb r7,[r1,r3] @ load byte of substring
cmp r6,r7 @ compare byte
bne 2f @ not equal
cmp r6,#0 @ string end ?
beq 3f @ yes
add r5,r5,#1 @ else increment index
add r3,r3,#1
b 1b @ and loop
2: @ characters not equal
cmp r6,#0 @ end string ?
beq 4f
cmp r7,#0 @ end substring ?
addeq r4,r4,#1 @ yes -> increment counter
mov r3,#0 @ raz index substring
add r5,r5,#1 @ increment string index
b 1b @ and loop
3: @ end string and end substring
add r4,r4,#1 @ increment counter
4: @ result display
mov r0,r4
ldr r1,iAdrsZoneConv
bl conversion10
ldr r0,iAdrszMessResult
bl affichageMess
ldr r0,iAdrsZoneConv
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
mov r0,r4
100:
pop {r1-r7,pc}
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../affichage.inc"
 
</syntaxhighlight>
{{Out}}
<pre>
Program 32 bits start.
Result: 3
Result: 2
</pre>
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">countOccurrences: function [str, substr]-> size match str substr
 
loop [["the three truths" "th"] ["ababababab" "abab"]] 'pair ->
Line 387 ⟶ 661:
~"occurrences of '|last pair|' in '|first pair|':"
countOccurrences first pair last pair
]</langsyntaxhighlight>
 
{{out}}
Line 398 ⟶ 672:
AutoHotkey has a rather unconventional method which outperforms this.
StringReplace sets the number of replaced strings to ErrorLevel.
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % countSubstring("the three truths","th") ; 3
MsgBox % countSubstring("ababababab","abab") ; 2
 
Line 404 ⟶ 678:
StringReplace, junk, fullstring, %substring%, , UseErrorLevel
return errorlevel
}</langsyntaxhighlight>
 
=={{header|AWK}}==
 
<syntaxhighlight lang="awk">#
<lang AWK>#
# countsubstring(string, pattern)
# Returns number of occurrences of pattern in string
Line 437 ⟶ 711:
print countsubstring_regex("[do&d~run?d!run&>run&]", "run[&]")
print countsubstring("the three truths","th")
}</langsyntaxhighlight>
{{out}}
<pre>$ awk -f countsubstring.awk
Line 446 ⟶ 720:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="qbasic">FUNCTION Uniq_Tally(text$, part$)
LOCAL x
WHILE TALLY(text$, part$)
Line 456 ⟶ 730:
 
PRINT "the three truths - th: ", Uniq_Tally("the three truths", "th")
PRINT "ababababab - abab: ", Uniq_Tally("ababababab", "abab")</langsyntaxhighlight>
{{out}}
<pre>
Line 468 ⟶ 742:
In FreeBASIC, this needs to be compiled with <code>-lang qb</code> or <code>-lang fblite</code>.
 
<langsyntaxhighlight lang="qbasic">DECLARE FUNCTION countSubstring& (where AS STRING, what AS STRING)
 
PRINT "the three truths, th:", countSubstring&("the three truths", "th")
Line 482 ⟶ 756:
LOOP
countSubstring = c
END FUNCTION</langsyntaxhighlight>
 
{{out}}
Line 489 ⟶ 763:
 
See also: [[#Liberty BASIC|Liberty BASIC]], [[#PowerBASIC|PowerBASIC]], [[#PureBasic|PureBasic]].
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">10 F$ = "TH"
20 S$ = "THE THREE TRUTHS"
30 GOSUB 100"COUNT SUBSTRING
Line 509 ⟶ 784:
170 IF F$ = MID$(S$, I, F) THEN R = R + 1 : I = I + F - 1
180 NEXT I
190 RETURN</langsyntaxhighlight>
 
==={{header|BASIC256}}===
{{trans|Run BASIC}}
<syntaxhighlight lang="freebasic">print countSubstring("the three truths","th")
print countSubstring("ababababab","abab")
end
 
function countSubstring(s$,find$)
i = 1
while instr(s$,find$,i) <> 0
countSubstring += 1
i = instr(s$,find$,i) + length(find$)
end while
end function</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de Run BASIC.</pre>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|Applesoft BASIC}}
{{works with|MSX_BASIC}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
{{trans|Applesoft BASIC}}
<syntaxhighlight lang="qbasic">10 CLS : REM 10 HOME for Applesoft BASIC
20 F$ = "TH"
30 S$ = "THE THREE TRUTHS"
40 GOSUB 110: REM COUNT SUBSTRING
50 PRINT R
60 F$ = "ABAB"
70 S$ = "ABABABABAB"
80 GOSUB 110: REM COUNT SUBSTRING
90 PRINT R
100 END
110 R = 0
120 F = LEN(F$)
130 S = LEN(S$)
140 IF F > S THEN RETURN
150 IF F = 0 THEN RETURN
160 IF F = S AND F$ = S$ THEN R = 1: RETURN
170 FOR I = 1 TO S - F
180 IF F$ = MID$(S$, I, F) THEN R = R + 1: I = I + F - 1
190 NEXT I
200 RETURN</syntaxhighlight>
 
==={{header|GW-BASIC}}===
The [[#Chipmunk_Basic|Chipmunk Basic]] solution works without any changes.
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 INPUT PROMPT "String: ":TXT$
110 INPUT PROMPT "Substring: ":SUB$
120 PRINT COUNT(LCASE$(TXT$),LCASE$(SUB$))
Line 522 ⟶ 844:
180 LOOP UNTIL PO=0
190 LET COUNT=N
200 END DEF</langsyntaxhighlight>
 
==={{header|MSX Basic}}===
The [[#Chipmunk_Basic|Chipmunk Basic]] solution works without any changes.
 
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM.
<langsyntaxhighlight lang="basic"> 10 LET S$="THE THREE TRUTHS"
20 LET U$="TH"
30 GOSUB 100
Line 542 ⟶ 867:
150 LET N=N+1
160 LET I=I+LEN U$
170 GOTO 130</langsyntaxhighlight>
 
==={{header|True BASIC}}===
{{trans|QBasic}}
<syntaxhighlight lang="qbasic">FUNCTION countsubstring(where$, what$)
LET c = 0
LET s = 1-LEN(what$)
DO
LET s = POS(where$,what$,s+LEN(what$))
IF 0 = s THEN EXIT DO
LET c = c+1
LOOP
LET countsubstring = c
END FUNCTION
 
PRINT "the three truths, th:", countSubstring("the three truths", "th")
PRINT "ababababab, abab:", countSubstring("ababababab", "abab")
END</syntaxhighlight>
 
==={{header|Yabasic}}===
{{trans|Run BASIC}}
<syntaxhighlight lang="yabasic">print countSubstring("the three truths","th")
print countSubstring("ababababab","abab")
end
 
sub countSubstring(s$,find$)
countSubstring = 0
i = 1
while instr(s$,find$,i) <> 0
countSubstring = countSubstring + 1
i = instr(s$,find$,i) + len(find$)
end while
return countSubstring
end sub</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de Run BASIC.</pre>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 565 ⟶ 925:
set input=!trimmed!
set /a cnt+=1
goto count_loop</langsyntaxhighlight>
{{Out}}
<pre>3
Line 571 ⟶ 931:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> tst$ = "the three truths"
sub$ = "th"
PRINT ; FNcountSubstring(tst$, sub$) " """ sub$ """ in """ tst$ """"
Line 587 ⟶ 947:
UNTIL I% = 0
= N%
</syntaxhighlight>
</lang>
{{out}}
<pre>3 "th" in "the three truths"
Line 593 ⟶ 953:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let countsubstr(str, match) = valof
Line 621 ⟶ 981:
show("ababababab", "abab")
show("cat", "dog")
$)</langsyntaxhighlight>
{{out}}
<pre>"th" in "the three truths": 3
"abab" in "ababababab": 2
"dog" in "cat": 0</pre>
 
=={{header|BQN}}==
<code>/𝕨⍷𝕩</code> finds locations of substrings, rest of the function suppresses overlapping substrings.
<syntaxhighlight lang="bqn">Find←{i←/𝕨⍷𝕩, i/˜i≥»0≤◶⟨⊣,(≠𝕨)+⊢⟩`i}
 
•Show "abab" Find "ababababab"
•Show "th" Find "the three truths"</syntaxhighlight>
<syntaxhighlight lang="text">2
3</syntaxhighlight>
 
Using strings.bqn from bqn-libs, another solution is <code>Find←+´Locate</code>, since <code>Locate</code> performs a non-overlapping search.
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat"> ( count-substring
= n S s p
. 0:?n:?p
Line 643 ⟶ 1,014:
& out$(count-substring$("the three truths".th))
& out$(count-substring$(ababababab.abab))
& ;</langsyntaxhighlight>
{{out}}
<pre>3
Line 649 ⟶ 1,020:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <string.h>
 
Line 670 ⟶ 1,041:
printf("not: %d\n", match("abababababa", "aba", 0));
return 0;
}</langsyntaxhighlight>
 
Alternate version:
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
 
Line 694 ⟶ 1,065:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 702 ⟶ 1,073:
</pre>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="c sharp">using System;
 
class SubStringTestClass
Line 728 ⟶ 1,099:
return count;
}
}</langsyntaxhighlight>
 
Using C# 6.0's expression-bodied member, null-conditional operator, and coalesce operator features:
 
<langsyntaxhighlight lang="c sharp">using System;
class SubStringTestClass
{
public static int CountSubStrings(this string testString, string testSubstring) =>
testString?.Split(new [] { testSubstring }, StringSplitOptions.None)?.Length - 1 ?? 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
 
Line 763 ⟶ 1,134:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 773 ⟶ 1,144:
=={{header|Clojure}}==
Use a sequence of regexp matches to count occurrences.
<langsyntaxhighlight lang="clojure">
(defn re-quote
"Produces a string that can be used to create a Pattern
Line 784 ⟶ 1,155:
(defn count-substring [txt sub]
(count (re-seq (re-pattern (re-quote sub)) txt)))
</syntaxhighlight>
</lang>
 
Use the trick of blank replacement and maths to count occurrences.
<langsyntaxhighlight lang="clojure">
(defn count-substring1 [txt sub]
(/ (- (count txt) (count (.replaceAll txt sub "")))
(count sub)))
</syntaxhighlight>
</lang>
 
A Java 8 stream-based solution, which should avoid creation of temporary strings
(though it will produce temporary MatchResult instances).
<langsyntaxhighlight lang="clojure">
(defn count-substring2 [txt sub]
(-> sub
Line 803 ⟶ 1,174:
(.results)
(.count)))
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
<code>INSPECT</code> can be used for this task without having to create a function.
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. testing.
 
Line 828 ⟶ 1,199:
 
GOBACK
.</langsyntaxhighlight>
 
{{out}}
Line 838 ⟶ 1,209:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
countSubstring = (str, substr) ->
n = 0
Line 849 ⟶ 1,220:
console.log countSubstring "the three truths", "th"
console.log countSubstring "ababababab", "abab"
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun count-sub (str pat)
(loop with z = 0 with s = 0 while s do
(when (setf s (search pat str :start2 s))
Line 859 ⟶ 1,230:
 
(count-sub "ababa" "ab") ; 2
(count-sub "ababa" "aba") ; 1</langsyntaxhighlight>
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub countSubstring(str: [uint8], match: [uint8]): (count: uint8) is
Line 888 ⟶ 1,259:
print_nl();
print_i8(countSubstring("cat","dog")); # should print 0
print_nl();</langsyntaxhighlight>
 
{{out}}
Line 897 ⟶ 1,268:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm;
 
"the three truths".count("th").writeln;
"ababababab".count("abab").writeln;
}</langsyntaxhighlight>
{{out}}
<pre>3
Line 908 ⟶ 1,279:
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program OccurrencesOfASubstring;
 
{$APPTYPE CONSOLE}
Line 930 ⟶ 1,301:
Writeln(CountSubstring('the three truths', 'th'));
Writeln(CountSubstring('ababababab', 'abab'));
end.</langsyntaxhighlight>
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc countSubstring(*char string, substring) word:
word count;
*char pos, loc;
count := 0;
while string* /= '\e' do
pos := substring;
loc := string;
while loc* = pos* do
loc := loc + 1;
pos := pos + 1
od;
if pos* = '\e' then
string := loc;
count := count + 1
else
string := string + 1
fi
od;
count
corp
 
proc main() void:
writeln(countSubstring("the three truths", "th"));
writeln(countSubstring("ababababab", "abab"))
corp</syntaxhighlight>
{{out}}
<pre>3
2</pre>
 
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">func countSubstring(str, val) {
var idx = 0
var count = 0
while true {
idx = str.indexOfIndexOf(val, idx)
if idx == -1 {
break
}
idx += val.lenLength()
count += 1
}
Line 949 ⟶ 1,351:
 
print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))</langsyntaxhighlight>
 
{{out}}
Line 957 ⟶ 1,359:
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">!. count "the three truths" "th"
!. count "ababababab" "abab"</langsyntaxhighlight>
{{out}}
<pre>3
2</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
func count str$ pat$ .
ind = 1
while ind + len pat$ - 1 <= len str$
if substr str$ ind len pat$ = pat$
cnt += 1
ind += len pat$
else
ind += 1
.
.
return cnt
.
print count "the three truths" "th"
print count "ababababab" "abab"
print count "11111111" "11"
print count "11111111" "12"
print count "12" "12"
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; from Racket
(define count-substring
Line 973 ⟶ 1,396:
(count-substring "/ .e/" "Longtemps je me suis couché de bonne heure") ;; regexp
→ 4
</syntaxhighlight>
</lang>
 
=={{header|EGL}}==
{{works with|EDT}}
The "remove and count the difference" and "manual loop" methods. Implementation includes protection from empty source and search strings.
<langsyntaxhighlight EGLlang="egl">program CountStrings
function main()
Line 1,029 ⟶ 1,452:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>Remove and Count:
Line 1,051 ⟶ 1,474:
 
=={{header|Eiffel}}==
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,087 ⟶ 1,510:
search_for:STRING = "abab"
end
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">countSubstring = fn(_, "") -> 0
(str, sub) -> length(String.split(str, sub)) - 1 end
 
Line 1,104 ⟶ 1,527:
Enum.each(data, fn{str, sub} ->
IO.puts countSubstring.(str, sub)
end)</langsyntaxhighlight>
 
{{out}}
Line 1,116 ⟶ 1,539:
0
0
</pre>
 
=={{header|Emacs Lisp}}==
Two Emacs Lisp solutions are shown below
<syntaxhighlight lang="lisp">
;; version 1, which takes advantage of the how-many function,
;; which runs only in a buffer
 
(defun count-substrings (text substring)
"Count non-overlapping occurrences of SUBSTRING in TEXT."
(with-temp-buffer ; create a temporary buffer, which will be deleted when function finishes
(insert text) ; insert TEXT into the empty buffer
(goto-char (point-min)) ; go to the beginning of the buffer
(how-many substring))) ; count how many occurrences of SUBSTRING
 
 
;; version 2, which operates on a string
 
(defun count-substrings (text substring)
"Count non-overlapping occurences of SUBSTRING in TEXT."
(let ((substrings)) ; empty list to add occurrences of SUBSTRING as we find them
(while (string-match substring text) ; as long as we can find SUBSTRING in TEXT
(push (match-string 0 text) substrings) ; add the SUBSTRING we found to the list of substrings
(setq text (replace-match "" nil nil text))) ; remove SUBSTRING from text, and repeat while loop
(length substrings))) ; count number of items in substrings list
</syntaxhighlight>
{{out}}
<pre>
(count-substrings "the three truths" "th")
3
 
(count-substrings "ababababab" "abab")
2
 
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
%% Count non-overlapping substrings in Erlang for the rosetta code wiki.
%% Implemented by J.W. Luiten
Line 1,147 ⟶ 1,604:
main(String, Sub) ->
match(String, Sub, Sub, 0).</langsyntaxhighlight>
Command: <langsyntaxhighlight Erlanglang="erlang">substrings:main("ababababab","abab").</langsyntaxhighlight>
{{out}}
<pre>
Line 1,155 ⟶ 1,612:
 
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.
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function countSubstring(sequence s, sequence sub)
integer from,count
count = 0
Line 1,176 ⟶ 1,633:
 
? countSubstring("the three truths","th")
? countSubstring("ababababab","abab")</langsyntaxhighlight>
 
{{out}}
Line 1,185 ⟶ 1,642:
=={{header|F_Sharp|F#}}==
"Remove and count the difference" method, as shown by J, Java, ...
<langsyntaxhighlight Fsharplang="fsharp">open System
 
let countSubstring (where :string) (what : string) =
Line 1,200 ⟶ 1,657:
show "ababababab" "abab"
show "abc" ""
0</langsyntaxhighlight>
<pre>countSubstring("the three truths", "th") = 3
countSubstring("ababababab", "abab") = 2
Line 1,206 ⟶ 1,663:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: math sequences splitting ;
: occurences ( seq subseq -- n ) split-subseq length 1 - ;</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: str-count ( s1 len s2 len -- n )
2swap 0 >r
begin 2over search
Line 1,218 ⟶ 1,675:
 
s" the three truths" s" th" str-count . \ 3
s" ababababab" s" abab" str-count . \ 2</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Example
implicit none
integer :: n
Line 1,249 ⟶ 1,706:
end do
end function
end program</langsyntaxhighlight>
{{out}}
<pre>3
Line 1,256 ⟶ 1,713:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function countSubstring(s As String, search As String) As Integer
Line 1,275 ⟶ 1,732:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,285 ⟶ 1,742:
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import util.Regex
 
def countSubstring( str, substr ) = Regex( substr ).findAllMatchIn( str ).length()
 
println( countSubstring("the three truths", "th") )
println( countSubstring("ababababab", "abab") )</langsyntaxhighlight>
 
{{out}}
Line 1,301 ⟶ 1,758:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Count_occurrences_of_a_substring}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
=={{header|FutureBasic}}==
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
<syntaxhighlight lang="futurebasic">window 1
 
local fn CountSubstring( string as CFStringRef, substring as CFStringRef ) as long
In '''[https://formulae.org/?example=Count_occurrences_of_a_substring this]''' page you can see the program(s) related to this task and their results.
end fn = fn ArrayCount( fn StringComponentsSeparatedByString( string, substring ) ) - 1
 
print fn CountSubstring( @"the three truths", @"th" )
print fn CountSubstring( @"ababababab", @"abab" )
 
HandleEvents</syntaxhighlight>
{{out}}
<pre>3
2
</pre>
 
=={{header|Gambas}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Public Sub Main()
Print countSubstring("the three truths", "th")
Print countSubstring("ababababab", "abab")
Print countSubString("zzzzzzzzzzzzzzz", "z")
 
End
 
Function countSubstring(s As String, search As String) As Integer
 
If s = "" Or search = "" Then Return 0
Dim count As Integer = 0, length As Integer = Len(search)
For i As Integer = 1 To Len(s)
If Mid(s, i, length) = Search Then
count += 1
i += length - 1
End If
Next
Return count
 
End Function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|Go}}==
Using strings.Count() method:
<langsyntaxhighlight lang="go">package main
import (
"fmt"
Line 1,318 ⟶ 1,812:
fmt.Println(strings.Count("the three truths", "th")) // says: 3
fmt.Println(strings.Count("ababababab", "abab")) // says: 2
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution, uses the Groovy "find" operator (=~), and the Groovy-extended Matcher property "count":
<langsyntaxhighlight lang="groovy">println (('the three truths' =~ /th/).count)
println (('ababababab' =~ /abab/).count)
println (('abaabba*bbaba*bbab' =~ /a*b/).count)
println (('abaabba*bbaba*bbab' =~ /a\*b/).count)</langsyntaxhighlight>
 
{{out}}
Line 1,335 ⟶ 1,829:
=={{header|Haskell}}==
=== Text-based solution ===
<langsyntaxhighlight lang="haskell">import Data.Text hiding (length)
 
-- Return the number of non-overlapping occurrences of sub in str.
Line 1,343 ⟶ 1,837:
print $ countSubStrs "the three truths" "th"
print $ countSubStrs "ababababab" "abab"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,351 ⟶ 1,845:
 
Alternatively, in a language built around currying, it might make more sense to reverse the suggested order of arguments.
<syntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}
<lang haskell>import Data.Text hiding (length)
 
import Data.Text hiding (length)
countAll :: String -> String -> Int
countAll needle haystack = length (breakOnAll n h)
where
[n, h] = pack <$> [needle, haystack]
 
--------- COUNT OF SUBSTRING INSTANCES IN A STRING -------
 
countAll :: Text -> Text -> Int
countAll needle haystack =
length
(breakOnAll needle haystack)
 
--------------------------- TEST -------------------------
main :: IO ()
main =
print $
print $ countAll "ab" <$> ["ababababab", "abelian absurdity", "babel kebab"]</lang>
countAll "ab"
 
<$> [ "ababababab",
"abelian absurdity",
"babel kebab"
]</syntaxhighlight>
{{Out}}
<pre>[5,2,2]</pre>
Line 1,368 ⟶ 1,871:
Even though list-based strings are not "the right" way of representing texts, the problem of counting subsequences in a list is generally useful.
 
<langsyntaxhighlight Haskelllang="haskell">count :: Eq a => [a] -> [a] -> Int
count [] = error "empty substring"
count sub = go
Line 1,376 ⟶ 1,879:
scan [] xs = 1 + go xs
scan (x:xs) (y:ys) | x == y = scan xs ys
| otherwise = go ys</langsyntaxhighlight>
{{Out}}
<pre>λ> count "th" "the three truths"
Line 1,390 ⟶ 1,893:
The following solution is almost two times faster than the previous one.
 
<langsyntaxhighlight Haskelllang="haskell">import Data.List (tails, stripPrefix)
import Data.Maybe (catMaybes)
 
count :: Eq a => [a] -> [a] -> Int
count sub = length . catMaybes . map (stripPrefix sub) . tails</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
every A := ![ ["the three truths","th"], ["ababababab","abab"] ] do
write("The string ",image(A[2])," occurs as a non-overlapping substring ",
Line 1,410 ⟶ 1,913:
}
return c
end</langsyntaxhighlight>
 
{{out}}
Line 1,418 ⟶ 1,921:
=={{header|J}}==
 
<langsyntaxhighlight lang="j">require'strings'
countss=: #@] %~ #@[ - [ #@rplc '';~]</langsyntaxhighlight>
 
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,425 ⟶ 1,928:
Example use:
 
<langsyntaxhighlight lang="j"> 'the three truths' countss 'th'
3
'ababababab' countss 'abab'
2</langsyntaxhighlight>
 
=={{header|Java}}==
Using regular expression pattern matching
<syntaxhighlight lang="java">
int countSubstring(String string, String substring) {
substring = Pattern.quote(substring);
Pattern pattern = Pattern.compile(substring);
Matcher matcher = pattern.matcher(string);
int count = 0;
while (matcher.find())
count++;
return count;
}
</syntaxhighlight>
<br />
{{works with|Java|1.5+}}
The "remove and count the difference" method:
<langsyntaxhighlight lang="java">public class CountSubstring {
public static int countSubstring(String subStr, String str){
return (str.length() - str.replace(subStr, "").length()) / subStr.length();
Line 1,443 ⟶ 1,959:
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}</langsyntaxhighlight>
{{out}}
<pre>3
Line 1,451 ⟶ 1,967:
{{works with|Java|1.5+}}
The "split and count" method:
<langsyntaxhighlight lang="java">import java.util.regex.Pattern;
 
public class CountSubstring {
Line 1,465 ⟶ 1,981:
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}</langsyntaxhighlight>
{{out}}
<pre>3
Line 1,472 ⟶ 1,988:
 
Manual looping
<langsyntaxhighlight lang="java">public class CountSubstring {
public static int countSubstring(String subStr, String str){
int count = 0;
Line 1,486 ⟶ 2,002:
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}</langsyntaxhighlight>
{{out}}
<pre>3
Line 1,494 ⟶ 2,010:
=={{header|JavaScript}}==
Using regexes:
<langsyntaxhighlight lang="javascript">function countSubstring(str, subStr) {
var matches = str.match(new RegExp(subStr, "g"));
return matches ? matches.length : 0;
}</langsyntaxhighlight>
 
Using 'split' and ES6 notation:
<langsyntaxhighlight lang="javascript">const countSubString = (str, subStr) => str.split(subStr).length - 1;
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Using regexes (available in jq versions after June 19, 2014):
<syntaxhighlight lang="jq">
<lang jq>
def countSubstring(sub):
[match(sub; "g")] | length;</langsyntaxhighlight>Example:<syntaxhighlight lang ="jq">
"the three truths" | countSubstring("th")</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 1,519 ⟶ 2,035:
 
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
ts = ["the three truths", "ababababab"]
tsub = ["th", "abab"]
Line 1,534 ⟶ 2,050:
println(length(matchall(Regex(tsub[i]), ts[i], true)))
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,549 ⟶ 2,065:
=={{header|K}}==
The dyadic verb _ss gives the positions of substring y in string x.
<langsyntaxhighlight Klang="k"> "the three truths" _ss "th"
0 4 13
 
Line 1,560 ⟶ 2,076:
#"ababababab" _ss "abab"
2
</syntaxhighlight>
</lang>
 
=={{header|Klingphix}}==
<langsyntaxhighlight Klingphixlang="klingphix">include ..\Utilitys.tlhy
 
:count %s !s
Line 1,575 ⟶ 2,091:
"ababababab" "abab" count ?
 
" " input</langsyntaxhighlight>
Other solution
<langsyntaxhighlight Klingphixlang="klingphix">include ..\Utilitys.tlhy
 
:count "- " convert "-" 2 tolist split len nip ;
Line 1,584 ⟶ 2,100:
"ababababab" "abab" count ?
 
" " input</langsyntaxhighlight>
{{out}}
<pre>3
Line 1,590 ⟶ 2,106:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun countSubstring(s: String, sub: String): Int = s.split(sub).size - 1
Line 1,598 ⟶ 2,114:
println(countSubstring("ababababab","abab"))
println(countSubstring("",""))
}</langsyntaxhighlight>
 
{{out}}
Line 1,608 ⟶ 2,124:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def countSubstring
{def countSubstring.r
Line 1,632 ⟶ 2,148:
{countSubstring aba ababa}
-> 1
</syntaxhighlight>
</lang>
 
=={{header|langur}}==
<langsyntaxhighlight lang="langur">writeln len indices q("th)", q("the three truths)"
writeln len indices q("abab)", q("ababababab)"</langsyntaxhighlight>
 
{{out}}
Line 1,643 ⟶ 2,159:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define countSubstring(str::string, substr::string)::integer => {
local(i = 1, foundpos = -1, found = 0)
while(#i < #str->size && #foundpos != 0) => {
Line 1,668 ⟶ 2,184:
//3
countSubstring_bothways('ababababab','abab')
//2</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print countSubstring( "the three truths", "th")
print countSubstring( "ababababab", "abab")
Line 1,685 ⟶ 2,201:
countSubstring =c
end function
</syntaxhighlight>
</lang>
 
=={{header|Logtalk}}==
Using atoms for string representation:
<langsyntaxhighlight lang="logtalk">
:- object(counting).
 
Line 1,707 ⟶ 2,223:
 
:- end_object.
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="text">
| ?- counting::count('the three truths', th, N).
N = 3
Line 1,717 ⟶ 2,233:
N = 2
yes
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
Solution 1:
 
<langsyntaxhighlight Lualang="lua">function countSubstring(s1, s2)
return select(2, s1:gsub(s2, ""))
end
 
print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))</langsyntaxhighlight>
<pre>3
2</pre>
Line 1,734 ⟶ 2,250:
Solution 2:
 
<langsyntaxhighlight Lualang="lua">function countSubstring(s1, s2)
local count = 0
for eachMatch in s1:gmatch(s2) do
Line 1,743 ⟶ 2,259:
 
print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))</langsyntaxhighlight>
<pre>3
2</pre>
 
=={{header|MACRO-11}}==
<syntaxhighlight lang="macro11"> .TITLE CSUBS
.MCALL .TTYOUT,.EXIT
CSUBS:: JMP DEMO
; COUNT SUBSTRINGS R1 IN R0
COUNT: CLR R2
BR 4$
1$: MOV R0,R3
MOV R1,R4
2$: CMPB (R3)+,(R4)+
BEQ 2$
TSTB -(R4)
BNE 3$
INC R2
DEC R3
MOV R3,R0
BR 4$
3$: INC R0
4$: TSTB (R0)
BNE 1$
RTS PC
; TEST EXAMPLES
DEMO: MOV #ST1,R0
MOV #SU1,R1
JSR PC,1$
MOV #ST2,R0
MOV #SU2,R1
JSR PC,1$
.EXIT
1$: JSR PC,COUNT
ADD #60,R2
MOVB R2,3$
MOV #3$,R2
2$: MOVB (R2)+,R0
.TTYOUT
BNE 2$
RTS PC
3$: .BYTE 0,15,12,0
 
ST1: .ASCIZ /THE THREE TRUTHS/
SU1: .ASCIZ /TH/
ST2: .ASCIZ /ABABABABAB/
SU2: .ASCIZ /ABAB/
.END CSUBS</syntaxhighlight>
{{out}}
<pre>3
2</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
f:=proc(s::string,c::string,count::nonnegint) local n;
n:=StringTools:-Search(c,s);
Line 1,758 ⟶ 2,324:
 
f("ababababab","abab",0);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,767 ⟶ 2,333:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">StringPosition["the three truths","th",Overlaps->False]//Length
3
StringPosition["ababababab","abab",Overlaps->False]//Length
2</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight Matlablang="matlab"> % Count occurrences of a substring without overlap
length(findstr("ababababab","abab",0))
length(findstr("the three truths","th",0))
 
% Count occurrences of a substring with overlap
length(findstr("ababababab","abab",1)) </langsyntaxhighlight>
 
{{out}}
Line 1,794 ⟶ 2,360:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">scount(e, s) := block(
[n: 0, k: 1],
while integerp(k: ssearch(e, s, k)) do (n: n + 1, k: k + 1),
Line 1,801 ⟶ 2,367:
 
scount("na", "banana");
2</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">string.count = function(s)
return self.split(s).len - 1
end function
 
print "the three truths".count("th")
print "ababababab".count("abab")</langsyntaxhighlight>
{{out}}
<pre>
Line 1,817 ⟶ 2,383:
 
=={{header|Mirah}}==
<langsyntaxhighlight lang="mirah">import java.util.regex.Pattern
import java.util.regex.Matcher
 
Line 1,855 ⟶ 2,421:
puts count_substring3("abab", "ababababab") # ==> 2
puts count_substring3("a*b", "abaabba*bbaba*bbab") # ==> 2
</syntaxhighlight>
</lang>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (show (countSubstring "the three truths" "th") ++ "\n"),
Stdout (show (countSubstring "ababababab" "abab") ++ "\n")]
 
countSubstring :: [*]->[*]->num
countSubstring str ss
= 0, if str = []
= 1 + countSubstring (drop len str) ss, if match
= countSubstring (tl str) ss, otherwise
where len = #ss
match = take len str = ss</syntaxhighlight>
{{out}}
<pre>3
2</pre>
 
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight Nanoquerylang="nanoquery">def countSubstring(str, subStr)
return int((len(str) - len(str.replace(subStr, ""))) / len(subStr))
end</langsyntaxhighlight>
 
=={{header|Nemerle}}==
{{trans|F#}}
<langsyntaxhighlight Nemerlelang="nemerle">using System.Console;
 
module CountSubStrings
Line 1,887 ⟶ 2,469:
WriteLine($"$target2 occurs $(text2.CountSubStrings(target2)) times in $text2");
}
}</langsyntaxhighlight>
{{out}}
<pre>th occurs 3 times in the three truths
Line 1,895 ⟶ 2,477:
NetRexx provides the <tt>''string''.countstr(''needle'')</tt> built-in function:
 
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,917 ⟶ 2,499:
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,926 ⟶ 2,508:
=={{header|NewLISP}}==
 
<langsyntaxhighlight NewLISPlang="newlisp">; file: stringcount.lsp
; url: http://rosettacode.org/wiki/Count_occurrences_of_a_substring
; author: oofoe 2012-01-29
Line 1,968 ⟶ 2,550:
)
 
(exit)</langsyntaxhighlight>
 
{{out}}
Line 1,981 ⟶ 2,563:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
proc count(s, sub: string): int =
Line 1,994 ⟶ 2,576:
echo count("the three truths","th")
 
echo count("ababababab","abab")</langsyntaxhighlight>
{{out}}
<pre>3
Line 2,001 ⟶ 2,583:
=={{header|Objective-C}}==
The "split and count" method:
<langsyntaxhighlight lang="objc">@interface NSString (CountSubstrings)
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
@end
Line 2,020 ⟶ 2,602:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>3
Line 2,028 ⟶ 2,610:
 
The "remove and count the difference" method:
<langsyntaxhighlight lang="objc">@interface NSString (CountSubstrings)
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
@end
Line 2,047 ⟶ 2,629:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>3
Line 2,055 ⟶ 2,637:
 
Manual looping:
<langsyntaxhighlight lang="objc">@interface NSString (CountSubstrings)
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
@end
Line 2,080 ⟶ 2,662:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>3
Line 2,088 ⟶ 2,670:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let count_substring str sub =
let sub_len = String.length sub in
let len_diff = (String.length str) - sub_len
Line 2,104 ⟶ 2,686:
Printf.printf "count 1: %d\n" (count_substring "the three truth" "th");
Printf.printf "count 2: %d\n" (count_substring "ababababab" "abab");
;;</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<syntaxhighlight lang="oforth">
<lang Oforth>
: countSubString(s, sub)
0 1 while(sub swap s indexOfAllFrom dup notNull) [ sub size + 1 under+ ]
drop ;</langsyntaxhighlight>
 
{{out}}
Line 2,122 ⟶ 2,704:
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
bag="the three truths"
x="th"
Line 2,135 ⟶ 2,717:
x="abab"
say left(bag,30) left(x,15) 'found' bag~caselesscountstr(x)
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:10ex;overflow:scroll">
Line 2,144 ⟶ 2,726:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">subvec(v,u)={
my(i=1,s);
while(i+#u<=#v,
Line 2,157 ⟶ 2,739:
substr(s1,s2)=subvec(Vec(s1),Vec(s2));
substr("the three truths","th")
substr("ababababab","abab")</langsyntaxhighlight>
{{out}}
<pre>%1 = 3
Line 2,166 ⟶ 2,748:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub countSubstring {
my $str = shift;
my $sub = quotemeta(shift);
Line 2,175 ⟶ 2,757:
print countSubstring("the three truths","th"), "\n"; # prints "3"
print countSubstring("ababababab","abab"), "\n"; # prints "2"</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="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: #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,199 ⟶ 2,781:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,211 ⟶ 2,793:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
Picat has a predicate for searching for substrings (find/4) but on backtracking (e.g. in a findall/2 wrapper) it yields all overlapping substrings which is not correct in this task.
 
So we have to roll our own. Here are two versions.
 
===Recursion===
<syntaxhighlight lang="picat">count_substrings_rec(S, SB) = C =>
count_rec(S,SB,0,C).
 
count_rec([],_SB,Count,Count).
count_rec(SBRest,SB,Count0,Count) :-
SBRest = SB ++ Rest, % "split" into substring and the rest of the string
count_rec(Rest,SB,Count0+1,Count).
count_rec([T|Rest],SB,Count0,Count) :-
T != SB, % this character is not a substring
count_rec(Rest,SB,Count0,Count).</syntaxhighlight>
 
===Iterative===
Iterative version using find/4 (wrap with once/1 to avoid backtracking).
{{trans|Euphoria}}
<syntaxhighlight lang="picat">count_substrings_find(S, SB) = C =>
SLen = S.len,
Count = 0,
From = 1,
while (From <= SLen)
(
once(find(slice(S,From),SB,_From2,To)) ->
Count := Count + 1,
From := From + To
;
From := From + 1
)
end,
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":
 
* count_substrings_rec/2: 0.009s
* count_substrings_find: 0.501s
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de countSubstring (Str Sub)
(let (Cnt 0 H (chop Sub))
(for (S (chop Str) S (cdr S))
Line 2,223 ⟶ 2,845:
(inc 'Cnt)
(setq S (map prog2 H S)) ) )
Cnt ) )</langsyntaxhighlight>
Test:
<pre>: (countSubstring "the three truths" "th")
Line 2,232 ⟶ 2,854:
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">
<lang Pike>
write("%d %d\n",
String.count("the three truths", "th"),
String.count("ababababab", "abab"));
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,243 ⟶ 2,865:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">cnt: procedure options (main);
declare (i, tally) fixed binary;
declare (text, key) character (100) varying;
Line 2,256 ⟶ 2,878:
end;
put skip list (tally);
end cnt;</langsyntaxhighlight>
 
Output for the two specified strings is as expected.
Line 2,267 ⟶ 2,889:
 
=={{header|PL/M}}==
<langsyntaxhighlight lang="plm">100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
Line 2,315 ⟶ 2,937:
 
CALL EXIT;
EOF</langsyntaxhighlight>
{{out}}
<pre>3
Line 2,331 ⟶ 2,953:
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.)
 
<langsyntaxhighlight lang="powerbasic">FUNCTION PBMAIN () AS LONG
PRINT "the three truths, th:", TALLY("the three truths", "th")
PRINT "ababababab, abab:", TALLY("ababababab", "abab")
END FUNCTION</langsyntaxhighlight>
 
{{out}}
Line 2,343 ⟶ 2,965:
 
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
[regex]::Matches("the three truths", "th").count
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,351 ⟶ 2,973:
</pre>
 
<syntaxhighlight lang="powershell">
<lang PowerShell>
[regex]::Matches("ababababab","abab").count
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,365 ⟶ 2,987:
Using SWI-Prolog's string facilities (this solution is very similar to the Logtalk solution that uses sub_atom/5):
 
<langsyntaxhighlight lang="prolog">
 
count_substring(String, Sub, Total) :-
Line 2,383 ⟶ 3,005:
DropN is Before + Length,
sub_string(String, DropN, Remain, 0, Rest).
</syntaxhighlight>
</lang>
 
Usage:
<langsyntaxhighlight lang="prolog">
?- count_substring("the three truths","th",X).
X = 3.
Line 2,392 ⟶ 3,014:
?- count_substring("ababababab","abab",X).
X = 2.
</syntaxhighlight>
</lang>
 
=== version using DCG ===
 
{{works with|SWI-Prolog|7.6.4}}
<langsyntaxhighlight lang="prolog">
:- system:set_prolog_flag(double_quotes,chars) .
 
Line 2,431 ⟶ 3,053:
.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,454 ⟶ 3,076:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">a = CountString("the three truths","th")
b = CountString("ababababab","abab")
; a = 3
; b = 2</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> "the three truths".count("th")
3
>>> "ababababab".count("abab")
2</langsyntaxhighlight>
 
=={{header|Quackery}}==
Line 2,469 ⟶ 3,091:
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.
 
<langsyntaxhighlight Quackerylang="quackery"> [ [] 95 times
[ i^ space +
join ] ] constant is alphabet ( --> $ )
Line 2,523 ⟶ 3,145:
else
[ swap buildfsm
usefsm ] ] is find$ ( $ $ --> n )</langsyntaxhighlight>
 
<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 positionpositions 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.)
 
<langsyntaxhighlight Quackerylang="quackery"> [ over size 0 = iff
[ 2drop [] ] done
[] unrot
Line 2,540 ⟶ 3,162:
nip swap again ]
2drop drop ] is findall$ ( $ $ --> [ )
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,557 ⟶ 3,179:
</pre>
 
Finally we calcan use <code>findall$</code> to fulfil the task requirements.
 
<langsyntaxhighlight Quackerylang="quackery"> [ swap findall$ size ] is occurences ( $ $ --> n )
 
$ "the three truths" $ "th" occurences echo cr
$ "ababababab" $ "abab" occurences echo cr
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,575 ⟶ 3,197:
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.
 
<langsyntaxhighlight lang="rsplus">count = function(haystack, needle)
{v = attr(gregexpr(needle, haystack, fixed = T)[[1]], "match.length")
if (identical(v, -1L)) 0 else length(v)}
 
print(count("hello", "l"))</langsyntaxhighlight>
 
{{libheader|stringr}}
 
<langsyntaxhighlight lang="rsplus">library(stringr)
print(str_count("hello", fixed("l")))</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
(define count-substring
(compose length regexp-match*))
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="racket">
> (count-substring "th" "the three truths")
3
> (count-substring "abab" "ababababab")
2
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub count-substring($big, $little) { +$big.comb: ~/ :r $little / }
 
say count-substring("the three truths", "th"); # 3
say count-substring("ababababab", "abab"); # 42
 
say count-substring(123123123, 12); # 3</langsyntaxhighlight>
The <tt>~:r</tt> prefixadverb operatormakes convertsthe <tt>$little</tt>regex to"ratchet aforward" <tt>Str</tt>and ifskip itany isn'toverlapping already, andmatches. <tt>.comb</tt> - when given a <tt>StrRegex</tt> as an argument - returns instances of that substring. You can think of it as if the argument was a regex that matched the string literally <tt>/$little/</tt>. 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}}==
<langsyntaxhighlight Redlang="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
]
 
;;-----------------------------------
test-case-1: "the three truths"
count-sub2: func [hay needle][
test-case-2: "ababababab"
;;-----------------------------------
 
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][
</syntaxhighlight>
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>
 
=={{header|Refal}}==
version 2
<syntaxhighlight lang="refal">$ENTRY Go {
hay: the three truths ,needle: th ,count: 3
= <Prout <Count ('th') 'the three truths'>>
hay: ababababab ,needle: abab ,count: 2
<Prout <Count ('abab') 'abababab'>>;
>> </pre>
};
 
Count {
(e.item) e.item e.rest = <+ 1 <Count (e.item) e.rest>>;
(e.item) s.x e.rest = <Count (e.item) e.rest>;
(e.item) = 0;
};</syntaxhighlight>
{{out}}
<pre>3
2</pre>
 
=={{header|REXX}}==
Line 2,660 ⟶ 3,279:
::::* &nbsp; too many arguments
::::* &nbsp; if &nbsp; '''start''' &nbsp; is a positive integer (when specified)
<langsyntaxhighlight lang="rexx">/*REXX program counts the occurrences of a (non─overlapping) substring in a string. */
w=. /*max. width so far.*/
bag= 'the three truths' ; x= "th" ; call showResult
Line 2,688 ⟶ 3,307:
if x=='' then x= " (null)" /* " " " " */
say left(bag, w) left(x, w%2) center(countstr(bag, x), 5)
return</langsyntaxhighlight>
'''output''' &nbsp; when using the default (internal) inputs:
<pre>
Line 2,705 ⟶ 3,324:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
<lang Ring>
aString = "Ring Welcome Ring to the Ring Ring Programming Ring Language Ring"
bString = "Ring"
Line 2,716 ⟶ 3,335:
cString = substr(cString,substr(cString,dString)+len(string(sum)))
end
return sum</langsyntaxhighlight>
 
Output:
<pre>
6
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
≪ DUP SIZE 1 - → str substr subsize
≪ 0
1 str SIZE subsize + '''FOR''' j
str j DUP subsize + SUB
'''IF''' substr == '''THEN'''
1 +
j subsize + 'j' STO
'''END'''
'''NEXT'''
≫ ≫ '<span style="color:blue">CNTSUB</span>' STO
 
"the three truths" <span style="color:blue">CNTSUB</span>
"ababababab" <span style="color:blue">CNTSUB</span>
{{out}}
<pre>
2: 3
1: 2
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def countSubstrings str, subStr
str.scan(subStr).length
end
 
p countSubstrings "the three truths", "th" #=> 3
p countSubstrings "ababababab", "abab" #=> 2</langsyntaxhighlight>
 
String#scan returns an array of substrings, and Array#length (or Array#size) counts them.
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">print countSubstring("the three truths","th")
print countSubstring("ababababab","abab")
 
Line 2,742 ⟶ 3,382:
i = instr(s$,find$,i) + len(find$)
WEND
END FUNCTION</langsyntaxhighlight>
{{out}}
<pre>3
Line 2,748 ⟶ 3,388:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
fn main() {
println!("{}","the three truths".matches("th").count());
println!("{}","ababababab".matches("abab").count());
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,762 ⟶ 3,402:
=={{header|Scala}}==
===Using Recursion===
<langsyntaxhighlight lang="scala">import scala.annotation.tailrec
def countSubstring(str1:String, str2:String):Int={
@tailrec def count(pos:Int, c:Int):Int={
Line 2,769 ⟶ 3,409:
}
count(0,0)
}</langsyntaxhighlight>
 
===Using Sliding===
<langsyntaxhighlight lang="scala">def countSubstring(str: String, sub: String): Int =
str.sliding(sub.length).count(_ == sub)</langsyntaxhighlight><br/>
 
===Using Regular Expressions===
<langsyntaxhighlight lang="scala">def countSubstring( str:String, substr:String ) = substr.r.findAllMatchIn(str).length</langsyntaxhighlight>
<br/>
<langsyntaxhighlight lang="scala">println(countSubstring("ababababab", "abab"))
println(countSubstring("the three truths", "th"))</langsyntaxhighlight>
{{out}}
<pre>2
Line 2,786 ⟶ 3,426:
=={{header|Scheme}}==
{{works with|Gauche Scheme}}
<langsyntaxhighlight Schemelang="scheme">gosh> (use gauche.lazy)
#<undef>
gosh> (length (lrxmatch "th" "the three truths"))
Line 2,792 ⟶ 3,432:
gosh> (length (lrxmatch "abab" "ababababab"))
2
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func integer: countSubstring (in string: stri, in string: searched) is func
Line 2,814 ⟶ 3,454:
writeln(countSubstring("the three truths", "th"));
writeln(countSubstring("ababababab", "abab"));
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,821 ⟶ 3,461:
2
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program count_overlapping_substrings;
tests := [["the three truths", "th"], ["ababababab", "abab"]];
loop for [s, subs] in tests do
print("'" + subs + "' in '" + s + "': "
+ str countSubs(s, subs));
end loop;
 
proc countSubs(s, subs);
count := 0;
loop while s(subs) /= om do
s(subs) := "";
count +:= 1;
end loop;
return count;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>'th' in 'the three truths': 3
'abab' in 'ababababab': 2</pre>
 
=={{header|SenseTalk}}==
'''Simply stated:'''
<langsyntaxhighlight lang="sensetalk">
put the number of occurrences of "th" in "the three truths" --> 3
put the number of occurrences of "abab" in "ababababab" -- > 2
</syntaxhighlight>
</lang>
'''User-created function:'''
<langsyntaxhighlight lang="sensetalk">
put countSubstring("aaaaa","a") // 5
put countSubstring("abababa","aba") // 2
Line 2,836 ⟶ 3,497:
return number of occurrences of subString in mainString
end countSubstring
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
'''Built-in:'''
<langsyntaxhighlight lang="ruby">say "the three truths".count("th");
say "ababababab".count("abab");</langsyntaxhighlight>
 
'''User-created function:'''
<langsyntaxhighlight lang="ruby">func countSubstring(s, ss) {
var re = Regex.new(ss.escape, 'g'); # 'g' for global
var counter = 0;
Line 2,852 ⟶ 3,513:
 
say countSubstring("the three truths","th");
say countSubstring("ababababab","abab");</langsyntaxhighlight>
{{out}}
<pre>
Line 2,859 ⟶ 3,520:
</pre>
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
INTEGER PROCEDURE COUNTSUBSTRING(T,TSUB); TEXT T,TSUB;
Line 2,878 ⟶ 3,539:
OUTINT(COUNTSUBSTRING("ABABABABAB", "ABAB"),0);
OUTIMAGE;
END.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,887 ⟶ 3,548:
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">Transcript showCR:('the three truths' occurrencesOfString:'th').
Transcript showCR:('ababababab' occurrencesOfString:'abab')</langsyntaxhighlight>
{{out}}
<pre>3
Line 2,894 ⟶ 3,555:
 
=={{header|SNOBOL4}}==
<syntaxhighlight lang="snobol4">
<lang SNOBOL4>
DEFINE("countSubstring(t,s)")
 
Line 2,906 ⟶ 3,567:
3
2
</syntaxhighlight>
</lang>
 
=={{header|Standard ML}}==
 
<langsyntaxhighlight lang="sml">fun count_substrings (str, sub) =
let
fun aux (str', count) =
Line 2,927 ⟶ 3,588:
print (Int.toString (count_substrings ("the three truths", "th")) ^ "\n");
print (Int.toString (count_substrings ("ababababab", "abab")) ^ "\n");
print (Int.toString (count_substrings ("abaabba*bbaba*bbab", "a*b")) ^ "\n");</langsyntaxhighlight>
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">function strcount(s, x) {
n = 0
k = 1-(i=strlen(x))
Line 2,943 ⟶ 3,604:
 
strcount("ababababab","abab")
2</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">import Foundation
 
func countSubstring(str: String, substring: String) -> Int {
Line 2,954 ⟶ 3,615:
 
print(countSubstring(str: "the three truths", substring: "th"))
print(countSubstring(str: "ababababab", substring: "abab"))</langsyntaxhighlight>
 
{{out}}
Line 2,963 ⟶ 3,624:
=={{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:
<langsyntaxhighlight lang="tcl">proc countSubstrings {haystack needle} {
regexp -all ***=$needle $haystack
}
puts [countSubstrings "the three truths" "th"]
puts [countSubstrings "ababababab" "abab"]
puts [countSubstrings "abaabba*bbaba*bbab" "a*b"]</langsyntaxhighlight>
{{out}}
<pre>3
2
2</pre>
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
 
MainModule: {
countSubstring: (λ s String() sub String()
(with n 0 pl 0
(while (> (= pl (find s sub pl)) -1)
(+= pl (size sub)) (+= n 1))
(lout n))
),
_start: (λ
(countSubstring "the three truths" "th")
(countSubstring "ababababab" "abab")
)
}</syntaxhighlight>{{out}}
<pre>
3
2
</pre>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT, {}
occurences=COUNT ("the three truths", ":th:")
occurences=COUNT ("ababababab", ":abab:")
occurences=COUNT ("abaabba*bbaba*bbab",":a\*b:")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,990 ⟶ 3,671:
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txr">@(next :args)
@(do (defun count-occurrences (haystack needle)
(for* ((occurrences 0)
Line 3,003 ⟶ 3,684:
@(output)
@(count-occurrences hay ndl) occurrences(s) of @ndl inside @hay
@(end)</langsyntaxhighlight>
 
<pre>$ ./txr count-occurrences.txr "baba" "babababa"
Line 3,012 ⟶ 3,693:
=={{header|UNIX Shell}}==
{{works with|Bash}}
<langsyntaxhighlight lang="bash">#!/bin/bash
 
function countString(){
Line 3,026 ⟶ 3,707:
 
countString "the three truths" "th"
countString "ababababab" "abab"</langsyntaxhighlight>
{{Out}}
<pre>3
Line 3,033 ⟶ 3,714:
=={{header|VBA}}==
 
<langsyntaxhighlight VBAlang="vba">Function CountStringInString(stLookIn As String, stLookFor As String)
CountStringInString = UBound(Split(stLookIn, stLookFor))
End Function</langsyntaxhighlight>
 
=={{header|VBScript}}==
'''user created function'''
<lang vb>
<syntaxhighlight lang="vb">
Function CountSubstring(str,substr)
CountSubstring = 0
Line 3,055 ⟶ 3,737:
WScript.StdOut.Write CountSubstring("the three truths","th") & vbCrLf
WScript.StdOut.Write CountSubstring("ababababab","abab") & vbCrLf
</syntaxhighlight>
</lang>
'''Using built-in Regexp'''
 
Run it with CScript.
<syntaxhighlight lang="vb">
function CountSubstring(str,substr)
with new regexp
.pattern=substr
.global=true
set m=.execute(str)
end with
CountSubstring =m.count
end function
WScript.StdOut.Writeline CountSubstring("the three truths","th")
WScript.StdOut.Writeline CountSubstring("ababababab","abab")
</syntaxhighlight>
{{Out}}
<pre>
Line 3,064 ⟶ 3,760:
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Module Count_Occurrences_of_a_Substring
Sub Main()
Console.WriteLine(CountSubstring("the three truths", "th"))
Line 3,083 ⟶ 3,779:
Return count
End Function
End Module</langsyntaxhighlight>
{{Out}}
<pre>3
Line 3,089 ⟶ 3,785:
2
0</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn main(){
println('the three truths'.count('th'))
println('ababababab'.count('abab'))
}</syntaxhighlight>
 
{{out}}
<pre>
3
2
</pre>
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@let {
c &[s t] #!s.match &(t)g
 
Line 3,098 ⟶ 3,806:
!!c "ababababab" "abab"
]]
}</langsyntaxhighlight>
Returns: <pre>[3 2]</pre>
 
Line 3,104 ⟶ 3,812:
{{libheader|Wren-pattern}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./pattern" for Pattern
import "./fmt" for Fmt
 
var countSubstring = Fn.new { |str, sub|
Line 3,123 ⟶ 3,831:
var count = countSubstring.call(test[0], test[1])
Fmt.print("$6s occurs $d times in $q.", Fmt.q(test[1]), count, test[0])
}</langsyntaxhighlight>
 
{{out}}
Line 3,133 ⟶ 3,841:
"b" occurs 0 times in "aaaaaaaaaaaaaa".
</pre>
 
Alternatively, using a library method (output same as before):
{{libheader|Wren-str}}
<syntaxhighlight lang="wren">import "./str" for Str
import "./fmt" for Fmt
 
var tests = [
["the three truths", "th"],
["ababababab", "abab"],
["abaabba*bbaba*bbab", "a*b"],
["aaaaaaaaaaaaaa", "aa"],
["aaaaaaaaaaaaaa", "b"],
]
 
for (test in tests) {
var count = Str.occurs(test[0], test[1])
Fmt.print("$6s occurs $d times in $q.", Fmt.q(test[1]), count, test[0])
}</syntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings, instead of MSb terminated
 
Line 3,175 ⟶ 3,901:
[IntOut(0, SubStr("the three truths", "th")); CrLf(0);
IntOut(0, SubStr("ababababab", "abab")); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,196 ⟶ 3,922:
=={{header|zkl}}==
Two solutions:
<langsyntaxhighlight lang="zkl">fcn countSubstring(s,p){ pn:=p.len(); cnt:=n:=0;
while(Void!=(n:=s.find(p,n))){cnt+=1; n+=pn}
cnt
}</langsyntaxhighlight>
{{trans|J}}
<langsyntaxhighlight lang="zkl">fcn countSubstring(s,p){ (pl:=p.len()) and (s.len()-(s-p).len())/pl }</langsyntaxhighlight>
{{out}}
<pre>
Line 3,213 ⟶ 3,939:
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 LET t$="ABABABABAB": LET p$="ABAB": GO SUB 1000
20 LET t$="THE THREE TRUTHS": LET p$="TH": GO SUB 1000
30 STOP
Line 3,222 ⟶ 3,948:
1040 NEXT i
1050 PRINT p$;"=";c''
1060 RETURN </langsyntaxhighlight>
29

edits