Count occurrences of a substring: Difference between revisions
Content deleted Content added
Not a robot (talk | contribs) Add 8080 assembly |
Added Uiua solution |
||
(67 intermediate revisions by 32 users not shown) | |||
Line 10:
It should return an integer count.
<
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2</
The matching should yield the highest number of non-overlapping matches.
Line 26:
=={{header|11l}}==
<
print(‘ababababab’.count(‘abab’))</
{{out}}
Line 37:
=={{header|360 Assembly}}==
The program uses two ASSIST macros (XDECO,XPRNT) to keep the code as short as possible.
<
COUNTSTR CSECT
USING COUNTSTR,R13 base register
Line 102:
* ---- -------------------------------------------------------
YREGS
END COUNTSTR</
{{out}}
<pre>
Line 115:
<code>DE</code>.
<
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</
{{out}}
<pre>320</pre>
=={{header|8086 Assembly}}==
<syntaxhighlight lang="asm"> cpu 8086
org 100h
section .text
jmp demo
;;; Count non-overlapping substrings [ES:DI] in [DS:SI]
;;; Return count in AX
subcnt: xor ax,ax ; Set count to 0
xor dl,dl ; Zero to compare to
mov bp,di ; Keep copy of substring pointer
.scan: cmp dl,[si] ; End of string?
je .out ; Then we're done
mov bx,si ; Keep copy of search position
mov di,bp ; Start at beginning of substring
.cmp: xor cx,cx
dec cx
repe cmpsb ; Scan until no match
dec si ; Go to first non-match
dec di
cmp dl,[es:di] ; Reached end of substring?
je .match ; Then we found a match
mov si,bx ; If not, continue searching one
inc si ; position further
jmp .scan
.match: inc ax ; Found a match - increment count
jmp .scan
.out: ret
;;; Test the routine on a few examples
demo: mov si,pairs
.loop: lodsw ; Load string pointer
test ax,ax ; If 0, stop
jz .out
xchg dx,ax
lodsw ; Load substring pointer
xchg di,ax
push si ; Keep example pointer
xchg si,dx
call subcnt ; Count substrings
call prax ; Print amount of substrings
pop si ; Restore example pointer
jmp .loop
.out: ret
;;; Print AX as number
prax: mov bx,num ; Pointer to end of number string
mov cx,10 ; Divisor
.dgt: xor dx,dx ; Divide by 10
div cx
add dl,'0' ; Add ASCII 0 to remainder
dec bx ; Store digit
mov [bx],dl
test ax,ax ; If number not zero yet
jnz .dgt ; Find rest of digits
mov dx,bx ; Print number string
mov ah,9
int 21h
ret
section .data
db '*****' ; Output number placeholder
num: db ' $'
;;; Examples
pairs: dw .str1,.sub1,.str2,.sub2,.str3,.sub3,0
.str1: db 'the three truths',0
.sub1: db 'th',0 ; result should be 3
.str2: db 'ababababab',0
.sub2: db 'abab',0 ; result should be 2
.str3: db 'cat',0
.sub3: db 'dog',0 ; result should be 0</syntaxhighlight>
{{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}}==
<
procedure Substrings is
Line 185 ⟶ 424:
Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => "ababababab",
Pattern => "abab"));
end Substrings;</
{{out}}
Line 191 ⟶ 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/>
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>
<syntaxhighlight lang="algol68">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 206 ⟶ 441:
);
print((
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
))
</syntaxhighlight>
{{out}}
<pre>
3 2 2
Line 219 ⟶ 454:
=={{header|Apex}}==
Apex example for 'Count occurrences of a substring'.
<syntaxhighlight lang="apex">
String substr = 'ABC';
String str = 'ABCZZZABCYABCABCXXABC';
Line 231 ⟶ 466:
}
System.debug('Count String : '+count);
</syntaxhighlight>
<pre>
Line 237 ⟶ 472:
</pre>
=={{header|
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">csubs←{0=x←⊃⍸⍺⍷⍵:0 ⋄ 1+⍺∇(¯1+x+⍴⍺)↓⍵}</syntaxhighlight>
{{out}}
<pre> 'th' 'abab' 'dog' csubs¨ 'the three truths' 'ababababab' 'cat'
3 2 0</pre>
=={{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 246 ⟶ 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.
<
on run
Line 274 ⟶ 518:
return oError's NSLocalizedDescription as text
end evalOSA</
{{out}}
Line 283 ⟶ 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.
<
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to theSubstring
Line 292 ⟶ 536:
end countSubstring
{countSubstring("the three truths", "th"), countSubstring("ababababab", "abab")}</
{{Out}}
<syntaxhighlight lang
=={{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}}==
<syntaxhighlight lang="rebol">countOccurrences: function [str, substr]-> size match str substr
loop [["the three truths" "th"] ["ababababab" "abab"]] 'pair ->
print [
~"occurrences of '|last pair|' in '|first pair|':"
countOccurrences first pair last pair
]</syntaxhighlight>
{{out}}
<pre>occurrences of 'th' in 'the three truths': 3
occurrences of 'abab' in 'ababababab': 2</pre>
=={{header|AutoHotkey}}==
Line 301 ⟶ 672:
AutoHotkey has a rather unconventional method which outperforms this.
StringReplace sets the number of replaced strings to ErrorLevel.
<
MsgBox % countSubstring("ababababab","abab") ; 2
Line 307 ⟶ 678:
StringReplace, junk, fullstring, %substring%, , UseErrorLevel
return errorlevel
}</
=={{header|AWK}}==
<syntaxhighlight lang="awk">#
# countsubstring(string, pattern)
# Returns number of occurrences of pattern in string
Line 340 ⟶ 711:
print countsubstring_regex("[do&d~run?d!run&>run&]", "run[&]")
print countsubstring("the three truths","th")
}</
{{out}}
<pre>$ awk -f countsubstring.awk
Line 349 ⟶ 720:
=={{header|BaCon}}==
<
LOCAL x
WHILE TALLY(text$, part$)
Line 359 ⟶ 730:
PRINT "the three truths - th: ", Uniq_Tally("the three truths", "th")
PRINT "ababababab - abab: ", Uniq_Tally("ababababab", "abab")</
{{out}}
<pre>
Line 371 ⟶ 742:
In FreeBASIC, this needs to be compiled with <code>-lang qb</code> or <code>-lang fblite</code>.
<
PRINT "the three truths, th:", countSubstring&("the three truths", "th")
Line 385 ⟶ 756:
LOOP
countSubstring = c
END FUNCTION</
{{out}}
Line 392 ⟶ 763:
See also: [[#Liberty BASIC|Liberty BASIC]], [[#PowerBASIC|PowerBASIC]], [[#PureBasic|PureBasic]].
==={{header|Applesoft BASIC}}===
<
20 S$ = "THE THREE TRUTHS"
30 GOSUB 100"COUNT SUBSTRING
Line 412 ⟶ 784:
170 IF F$ = MID$(S$, I, F) THEN R = R + 1 : I = I + F - 1
180 NEXT I
190 RETURN</
==={{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}}===
<
110 INPUT PROMPT "Substring: ":SUB$
120 PRINT COUNT(LCASE$(TXT$),LCASE$(SUB$))
Line 425 ⟶ 844:
180 LOOP UNTIL PO=0
190 LET COUNT=N
200 END DEF</
==={{header|MSX Basic}}===
The [[#Chipmunk_Basic|Chipmunk Basic]] solution works without any changes.
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM.
<
20 LET U$="TH"
30 GOSUB 100
Line 445 ⟶ 867:
150 LET N=N+1
160 LET I=I+LEN U$
170 GOTO 130</
==={{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}}==
<
setlocal enabledelayedexpansion
Line 468 ⟶ 925:
set input=!trimmed!
set /a cnt+=1
goto count_loop</
{{Out}}
<pre>3
Line 474 ⟶ 931:
=={{header|BBC BASIC}}==
<
sub$ = "th"
PRINT ; FNcountSubstring(tst$, sub$) " """ sub$ """ in """ tst$ """"
Line 490 ⟶ 947:
UNTIL I% = 0
= N%
</syntaxhighlight>
{{out}}
<pre>3 "th" in "the three truths"
2 "abab" in "ababababab"</pre>
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
let countsubstr(str, match) = valof
$( let i, count = 1, 0
while i <= str%0 do
test valof
$( for j = 1 to match%0
unless match%j = str%(i+j-1)
resultis false
resultis true
$)
then
$( count := count + 1
i := i + match%0
$)
else
i := i + 1
resultis count
$)
let show(str, match) be
writef("*"%S*" in *"%S*": %N*N",
match, str, countsubstr(str, match))
let start() be
$( show("the three truths", "th")
show("ababababab", "abab")
show("cat", "dog")
$)</syntaxhighlight>
{{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}}==
<
= n S s p
. 0:?n:?p
Line 511 ⟶ 1,014:
& out$(count-substring$("the three truths".th))
& out$(count-substring$(ababababab.abab))
& ;</
{{out}}
<pre>3
Line 517 ⟶ 1,020:
=={{header|C}}==
<
#include <string.h>
Line 538 ⟶ 1,041:
printf("not: %d\n", match("abababababa", "aba", 0));
return 0;
}</
Alternate version:
<
#include <string.h>
Line 562 ⟶ 1,065:
return 0;
}</
{{out}}
<pre>
Line 570 ⟶ 1,073:
</pre>
=={{header|C sharp|C#}}==
<
class SubStringTestClass
Line 596 ⟶ 1,099:
return count;
}
}</
Using C# 6.0's expression-bodied member, null-conditional operator, and coalesce operator features:
<
class SubStringTestClass
{
public static int CountSubStrings(this string testString, string testSubstring) =>
testString?.Split(new [] { testSubstring }, StringSplitOptions.None)?.Length - 1 ?? 0;
}</
=={{header|C++}}==
<
#include <string>
Line 631 ⟶ 1,134:
return 0;
}</
{{out}}
<pre>
Line 641 ⟶ 1,144:
=={{header|Clojure}}==
Use a sequence of regexp matches to count occurrences.
<
(defn re-quote
"Produces a string that can be used to create a Pattern
that would match the string text as if it were a literal pattern.
Metacharacters or escape sequences in text will be given no special
meaning"
[text]
(java.util.regex.Pattern/quote text))
(defn count-substring [txt sub]
(count (re-seq (re-pattern (re-quote sub)) txt)))
</syntaxhighlight>
Use the trick of blank replacement and maths to count occurrences.
<
(defn count-substring1 [txt sub]
(/ (- (count txt) (count (.replaceAll txt sub "")))
(count sub)))
</syntaxhighlight>
A Java 8 stream-based solution, which should avoid creation of temporary strings
(though it will produce temporary MatchResult instances).
<syntaxhighlight lang="clojure">
(defn count-substring2 [txt sub]
(-> sub
(re-quote)
(re-pattern)
(re-matcher txt)
(.results)
(.count)))
</syntaxhighlight>
=={{header|COBOL}}==
<code>INSPECT</code> can be used for this task without having to create a function.
<
PROGRAM-ID. testing.
Line 676 ⟶ 1,199:
GOBACK
.</
{{out}}
Line 686 ⟶ 1,209:
=={{header|CoffeeScript}}==
<
countSubstring = (str, substr) ->
n = 0
Line 697 ⟶ 1,220:
console.log countSubstring "the three truths", "th"
console.log countSubstring "ababababab", "abab"
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(loop with z = 0 with s = 0 while s do
(when (setf s (search pat str :start2 s))
Line 707 ⟶ 1,230:
(count-sub "ababa" "ab") ; 2
(count-sub "ababa" "aba") ; 1</
=={{header|Cowgol}}==
<
sub countSubstring(str: [uint8], match: [uint8]): (count: uint8) is
Line 736 ⟶ 1,259:
print_nl();
print_i8(countSubstring("cat","dog")); # should print 0
print_nl();</
{{out}}
Line 745 ⟶ 1,268:
=={{header|D}}==
<
import std.stdio, std.algorithm;
"the three truths".count("th").writeln;
"ababababab".count("abab").writeln;
}</
{{out}}
<pre>3
Line 756 ⟶ 1,279:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 778 ⟶ 1,301:
Writeln(CountSubstring('the three truths', 'th'));
Writeln(CountSubstring('ababababab', 'abab'));
end.</
=={{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}}==
<
var idx = 0
var count = 0
while true {
idx = str.
if idx == -1 {
break
}
idx += val.
count += 1
}
Line 797 ⟶ 1,351:
print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))</
{{out}}
Line 805 ⟶ 1,359:
=={{header|Déjà Vu}}==
<
!. count "ababababab" "abab"</
{{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}}==
<
;; from Racket
(define count-substring
Line 821 ⟶ 1,396:
(count-substring "/ .e/" "Longtemps je me suis couché de bonne heure") ;; regexp
→ 4
</syntaxhighlight>
=={{header|ed}}==
<syntaxhighlight lang="sed">
H
,p
# Change the substring here to search it
g/th/s//^/g
g/[^^]/s///g
g/\^/s//i/g
,j
# unary -> decimal (up to 10^10)
g/i/s/^\(i*\)\1\1\1\1\1\1\1\1\1\(i\{0,9\}\)/\1 \2/
g/i/s/^\(i*\)\1\1\1\1\1\1\1\1\1\(i\{0,9\}\)/\1 \2/
g/i/s/^\(i*\)\1\1\1\1\1\1\1\1\1\(i\{0,9\}\)/\1 \2/
g/i/s/^\(i*\)\1\1\1\1\1\1\1\1\1\(i\{0,9\}\)/\1 \2/
g/i/s/^\(i*\)\1\1\1\1\1\1\1\1\1\(i\{0,9\}\)/\1 \2/
g/i/s/^\(i*\)\1\1\1\1\1\1\1\1\1\(i\{0,9\}\)/\1 \2/
g/i/s/^\(i*\)\1\1\1\1\1\1\1\1\1\(i\{0,9\}\)/\1 \2/
g/i/s/^\(i*\)\1\1\1\1\1\1\1\1\1\(i\{0,9\}\)/\1 \2/
g/i/s/^\(i*\)\1\1\1\1\1\1\1\1\1\(i\{0,9\}\)/\1 \2/
g/i/s/^\(i*\)\1\1\1\1\1\1\1\1\1\(i\{0,9\}\)/\1 \2/
g/i/s/[ ]$/ 0 /g
g/i/s/[ ][ ]/ 0 /g
g/i/s/[ ][ ]/ 0 /g
g/i/s/[ ]iiiiiiiii\>/ 9 /g
g/i/s/[ ]iiiiiiii\>/ 8 /g
g/i/s/[ ]iiiiiii\>/ 7 /g
g/i/s/[ ]iiiiii\>/ 6 /g
g/i/s/[ ]iiiii\>/ 5 /g
g/i/s/[ ]iiii\>/ 4 /g
g/i/s/[ ]iii\>/ 3 /g
g/i/s/[ ]ii\>/ 2 /g
g/i/s/[ ]i\>/ 1 /g
g/[ ]/s///g
g/^0\{1,\}\([0-9]\)/s//\1/
,p
Q
</syntaxhighlight>
{{out}}
<pre>$ ed -s count-substrings.input < count-substrings.ed
Newline appended
the three truths
3</pre>
=={{header|EGL}}==
{{works with|EDT}}
The "remove and count the difference" and "manual loop" methods. Implementation includes protection from empty source and search strings.
<
function main()
Line 877 ⟶ 1,498:
end
</syntaxhighlight>
{{out}}
<pre>Remove and Count:
Line 899 ⟶ 1,520:
=={{header|Eiffel}}==
<
class
APPLICATION
Line 935 ⟶ 1,556:
search_for:STRING = "abab"
end
</syntaxhighlight>
=={{header|Elixir}}==
<
(str, sub) -> length(String.split(str, sub)) - 1 end
Line 952 ⟶ 1,573:
Enum.each(data, fn{str, sub} ->
IO.puts countSubstring.(str, sub)
end)</
{{out}}
Line 964 ⟶ 1,585:
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">
%% Count non-overlapping substrings in Erlang for the rosetta code wiki.
%% Implemented by J.W. Luiten
Line 995 ⟶ 1,650:
main(String, Sub) ->
match(String, Sub, Sub, 0).</
Command: <
{{out}}
<pre>
Line 1,003 ⟶ 1,658:
Alternative using built in functions:
<syntaxhighlight lang="erlang">
main( String, Sub ) -> erlang:length( binary:split(binary:list_to_bin(String), binary:list_to_bin(Sub), [global]) ) - 1.
</syntaxhighlight>
=={{header|Euphoria}}==
<
integer from,count
count = 0
Line 1,024 ⟶ 1,679:
? countSubstring("the three truths","th")
? countSubstring("ababababab","abab")</
{{out}}
Line 1,033 ⟶ 1,688:
=={{header|F_Sharp|F#}}==
"Remove and count the difference" method, as shown by J, Java, ...
<
let countSubstring (where :string) (what : string) =
Line 1,048 ⟶ 1,703:
show "ababababab" "abab"
show "abc" ""
0</
<pre>countSubstring("the three truths", "th") = 3
countSubstring("ababababab", "abab") = 2
Line 1,054 ⟶ 1,709:
=={{header|Factor}}==
<
: occurences ( seq subseq -- n ) split-subseq length 1 - ;</
=={{header|Forth}}==
<
2swap 0 >r
begin 2over search
Line 1,066 ⟶ 1,721:
s" the three truths" s" th" str-count . \ 3
s" ababababab" s" abab" str-count . \ 2</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
integer :: n
Line 1,097 ⟶ 1,752:
end do
end function
end program</
{{out}}
<pre>3
Line 1,104 ⟶ 1,759:
=={{header|FreeBASIC}}==
<
Function countSubstring(s As String, search As String) As Integer
Line 1,123 ⟶ 1,778:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,133 ⟶ 1,788:
=={{header|FunL}}==
<
def countSubstring( str, substr ) = Regex( substr ).findAllMatchIn( str ).length()
println( countSubstring("the three truths", "th") )
println( countSubstring("ababababab", "abab") )</
{{out}}
Line 1,149 ⟶ 1,804:
=={{header|Fōrmulæ}}==
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">window 1
local fn CountSubstring( string as CFStringRef, substring as CFStringRef ) as long
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:
<
import (
"fmt"
Line 1,166 ⟶ 1,858:
fmt.Println(strings.Count("the three truths", "th")) // says: 3
fmt.Println(strings.Count("ababababab", "abab")) // says: 2
}</
=={{header|Groovy}}==
Solution, uses the Groovy "find" operator (=~), and the Groovy-extended Matcher property "count":
<
println (('ababababab' =~ /abab/).count)
println (('abaabba*bbaba*bbab' =~ /a*b/).count)
println (('abaabba*bbaba*bbab' =~ /a\*b/).count)</
{{out}}
Line 1,183 ⟶ 1,875:
=={{header|Haskell}}==
=== Text-based solution ===
<
-- Return the number of non-overlapping occurrences of sub in str.
Line 1,191 ⟶ 1,883:
print $ countSubStrs "the three truths" "th"
print $ countSubStrs "ababababab" "abab"
</syntaxhighlight>
{{out}}
<pre>
Line 1,199 ⟶ 1,891:
Alternatively, in a language built around currying, it might make more sense to reverse the suggested order of arguments.
<syntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}
import Data.Text hiding (length)
--------- COUNT OF SUBSTRING INSTANCES IN A STRING -------
countAll :: Text -> Text -> Int
countAll needle haystack =
length
(breakOnAll needle haystack)
--------------------------- TEST -------------------------
main :: IO ()
main =
print $
countAll "ab"
<$> [ "ababababab",
"abelian absurdity",
"babel kebab"
]</syntaxhighlight>
{{Out}}
<pre>[5,2,2]</pre>
Line 1,216 ⟶ 1,917:
Even though list-based strings are not "the right" way of representing texts, the problem of counting subsequences in a list is generally useful.
<
count [] = error "empty substring"
count sub = go
Line 1,224 ⟶ 1,925:
scan [] xs = 1 + go xs
scan (x:xs) (y:ys) | x == y = scan xs ys
| otherwise = go ys</
{{Out}}
<pre>λ> count "th" "the three truths"
Line 1,238 ⟶ 1,939:
The following solution is almost two times faster than the previous one.
<
import Data.Maybe (catMaybes)
count :: Eq a => [a] -> [a] -> Int
count sub = length . catMaybes . map (stripPrefix sub) . tails</
=={{header|Icon}} and {{header|Unicon}}==
<
every A := ![ ["the three truths","th"], ["ababababab","abab"] ] do
write("The string ",image(A[2])," occurs as a non-overlapping substring ",
Line 1,258 ⟶ 1,959:
}
return c
end</
{{out}}
Line 1,266 ⟶ 1,967:
=={{header|J}}==
<
countss=: #@] %~ #@[ - [ #@rplc '';~]</
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,273 ⟶ 1,974:
Example use:
<
3
'ababababab' countss 'abab'
2</
=={{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:
<
public static int countSubstring(String subStr, String str){
return (str.length() - str.replace(subStr, "").length()) / subStr.length();
Line 1,291 ⟶ 2,005:
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}</
{{out}}
<pre>3
Line 1,299 ⟶ 2,013:
{{works with|Java|1.5+}}
The "split and count" method:
<
public class CountSubstring {
Line 1,313 ⟶ 2,027:
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}</
{{out}}
<pre>3
Line 1,320 ⟶ 2,034:
Manual looping
<
public static int countSubstring(String subStr, String str){
int count = 0;
Line 1,334 ⟶ 2,048:
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}</
{{out}}
<pre>3
Line 1,342 ⟶ 2,056:
=={{header|JavaScript}}==
Using regexes:
<
var matches = str.match(new RegExp(subStr, "g"));
return matches ? matches.length : 0;
}</
Using 'split' and ES6 notation:
<
</syntaxhighlight>
=={{header|jq}}==
Using regexes (available in jq versions after June 19, 2014):
<syntaxhighlight lang="jq">
def countSubstring(sub):
[match(sub; "g")] | length;</
"the three truths" | countSubstring("th")</
=={{header|Julia}}==
Line 1,367 ⟶ 2,081:
'''Main'''
<syntaxhighlight lang="julia">
ts = ["the three truths", "ababababab"]
tsub = ["th", "abab"]
Line 1,382 ⟶ 2,096:
println(length(matchall(Regex(tsub[i]), ts[i], true)))
end
</syntaxhighlight>
{{out}}
Line 1,397 ⟶ 2,111:
=={{header|K}}==
The dyadic verb _ss gives the positions of substring y in string x.
<
0 4 13
Line 1,408 ⟶ 2,122:
#"ababababab" _ss "abab"
2
</syntaxhighlight>
=={{header|Klingphix}}==
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy
:count %s !s
0 >ps
[ps> 1 + >ps
$s len nip + snip nip] [$s find dup] while
drop drop ps>
;
"the three truths" "th" count ?
"ababababab" "abab" count ?
" " input</syntaxhighlight>
Other solution
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy
:count "- " convert "-" 2 tolist split len nip ;
"the three truths" "th" count ?
"ababababab" "abab" count ?
" " input</syntaxhighlight>
{{out}}
<pre>3
2</pre>
=={{header|Kotlin}}==
<
fun countSubstring(s: String, sub: String): Int = s.split(sub).size - 1
Line 1,419 ⟶ 2,160:
println(countSubstring("ababababab","abab"))
println(countSubstring("",""))
}</
{{out}}
Line 1,429 ⟶ 2,170:
=={{header|Lambdatalk}}==
<
{def countSubstring
{def countSubstring.r
Line 1,453 ⟶ 2,194:
{countSubstring aba ababa}
-> 1
</syntaxhighlight>
=={{header|langur}}==
<
writeln len
</syntaxhighlight>
{{out}}
Line 1,464 ⟶ 2,206:
=={{header|Lasso}}==
<
local(i = 1, foundpos = -1, found = 0)
while(#i < #str->size && #foundpos != 0) => {
Line 1,489 ⟶ 2,231:
//3
countSubstring_bothways('ababababab','abab')
//2</
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
print countSubstring( "the three truths", "th")
print countSubstring( "ababababab", "abab")
Line 1,506 ⟶ 2,248:
countSubstring =c
end function
</syntaxhighlight>
=={{header|Logtalk}}==
Using atoms for string representation:
<
:- object(counting).
Line 1,528 ⟶ 2,270:
:- end_object.
</syntaxhighlight>
{{out}}
<
| ?- counting::count('the three truths', th, N).
N = 3
Line 1,538 ⟶ 2,280:
N = 2
yes
</syntaxhighlight>
=={{header|Lua}}==
Solution 1:
<
return select(2, s1:gsub(s2, ""))
end
print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))</
<pre>3
2</pre>
Line 1,555 ⟶ 2,297:
Solution 2:
<
local count = 0
for eachMatch in s1:gmatch(s2) do
Line 1,564 ⟶ 2,306:
print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))</
<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">
f:=proc(s::string,c::string,count::nonnegint) local n;
n:=StringTools:-Search(c,s);
Line 1,579 ⟶ 2,371:
f("ababababab","abab",0);
</syntaxhighlight>
{{out}}
<pre>
Line 1,588 ⟶ 2,380:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
3
StringPosition["ababababab","abab",Overlaps->False]//Length
2</
=={{header|MATLAB}} / {{header|Octave}}==
<
length(findstr("ababababab","abab",0))
length(findstr("the three truths","th",0))
% Count occurrences of a substring with overlap
length(findstr("ababababab","abab",1)) </
{{out}}
Line 1,615 ⟶ 2,407:
=={{header|Maxima}}==
<
[n: 0, k: 1],
while integerp(k: ssearch(e, s, k)) do (n: n + 1, k: k + 1),
Line 1,622 ⟶ 2,414:
scount("na", "banana");
2</
=={{header|MiniScript}}==
<
return self.split(s).len - 1
end function
print "the three truths".count("th")
print "ababababab".count("abab")</
{{out}}
<pre>
Line 1,638 ⟶ 2,430:
=={{header|Mirah}}==
<
import java.util.regex.Matcher
Line 1,676 ⟶ 2,468:
puts count_substring3("abab", "ababababab") # ==> 2
puts count_substring3("a*b", "abaabba*bbaba*bbab") # ==> 2
</syntaxhighlight>
=={{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}}
<
return int((len(str) - len(str.replace(subStr, ""))) / len(subStr))
end</
=={{header|Nemerle}}==
{{trans|F#}}
<
module CountSubStrings
Line 1,708 ⟶ 2,516:
WriteLine($"$target2 occurs $(text2.CountSubStrings(target2)) times in $text2");
}
}</
{{out}}
<pre>th occurs 3 times in the three truths
Line 1,716 ⟶ 2,524:
NetRexx provides the <tt>''string''.countstr(''needle'')</tt> built-in function:
<
options replace format comments java crossref symbols nobinary
Line 1,738 ⟶ 2,546:
return
</syntaxhighlight>
{{out}}
<pre>
Line 1,747 ⟶ 2,555:
=={{header|NewLISP}}==
<
; url: http://rosettacode.org/wiki/Count_occurrences_of_a_substring
; author: oofoe 2012-01-29
Line 1,789 ⟶ 2,597:
)
(exit)</
{{out}}
Line 1,802 ⟶ 2,610:
=={{header|Nim}}==
<
proc count(s, sub: string): int =
Line 1,815 ⟶ 2,623:
echo count("the three truths","th")
echo count("ababababab","abab")</
{{out}}
<pre>3
Line 1,822 ⟶ 2,630:
=={{header|Objective-C}}==
The "split and count" method:
<
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
@end
Line 1,841 ⟶ 2,649:
}
return 0;
}</
{{out}}
<pre>3
Line 1,849 ⟶ 2,657:
The "remove and count the difference" method:
<
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
@end
Line 1,868 ⟶ 2,676:
}
return 0;
}</
{{out}}
<pre>3
Line 1,876 ⟶ 2,684:
Manual looping:
<
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
@end
Line 1,901 ⟶ 2,709:
}
return 0;
}</
{{out}}
<pre>3
Line 1,909 ⟶ 2,717:
=={{header|OCaml}}==
<
let sub_len = String.length sub in
let len_diff = (String.length str) - sub_len
Line 1,925 ⟶ 2,733:
Printf.printf "count 1: %d\n" (count_substring "the three truth" "th");
Printf.printf "count 2: %d\n" (count_substring "ababababab" "abab");
;;</
=={{header|Oforth}}==
<syntaxhighlight lang="oforth">
: countSubString(s, sub)
0 1 while(sub swap s indexOfAllFrom dup notNull) [ sub size + 1 under+ ]
drop ;</
{{out}}
Line 1,943 ⟶ 2,751:
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
bag="the three truths"
x="th"
Line 1,956 ⟶ 2,764:
x="abab"
say left(bag,30) left(x,15) 'found' bag~caselesscountstr(x)
</syntaxhighlight>
{{out}}
<pre style="height:10ex;overflow:scroll">
Line 1,965 ⟶ 2,773:
=={{header|PARI/GP}}==
<
my(i=1,s);
while(i+#u<=#v,
Line 1,978 ⟶ 2,786:
substr(s1,s2)=subvec(Vec(s1),Vec(s2));
substr("the three truths","th")
substr("ababababab","abab")</
{{out}}
<pre>%1 = 3
Line 1,985 ⟶ 2,793:
=={{header|Pascal}}==
See [[Count_occurrences_of_a_substring#Delphi | Delphi]]
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
function CountSubstrings(s,subs: string): integer := s.IndicesOf(subs).Count;
begin
Print(CountSubstrings('the three truths','th'));
Print(CountSubstrings('ababababab','abab'));
end.
</syntaxhighlight>
{{out}}
<pre>
3 2
</pre>
=={{header|Perl}}==
<
my $str = shift;
my $sub = quotemeta(shift);
Line 1,996 ⟶ 2,818:
print countSubstring("the three truths","th"), "\n"; # prints "3"
print countSubstring("ababababab","abab"), "\n"; # prints "2"</
=={{header|Phix}}==
<!--<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: #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;">"aba"</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;">"ab"</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;">"a"</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;">""</span><span style="color: #0000FF;">}}</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">start</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">count</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">substring</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">start</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">test</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">substring</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">start</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">substring</span><span style="color: #0000FF;">,</span><span style="color: #000000;">test</span><span style="color: #0000FF;">,</span><span style="color: #000000;">start</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">start</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">start</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">length</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;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,030 ⟶ 2,854:
=={{header|PHP}}==
<
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
</syntaxhighlight>
=={{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}}==
<
(let (Cnt 0 H (chop Sub))
(for (S (chop Str) S (cdr S))
Line 2,042 ⟶ 2,906:
(inc 'Cnt)
(setq S (map prog2 H S)) ) )
Cnt ) )</
Test:
<pre>: (countSubstring "the three truths" "th")
Line 2,051 ⟶ 2,915:
=={{header|Pike}}==
<syntaxhighlight lang="pike">
write("%d %d\n",
String.count("the three truths", "th"),
String.count("ababababab", "abab"));
</syntaxhighlight>
{{Out}}
<pre>
Line 2,062 ⟶ 2,926:
=={{header|PL/I}}==
<
declare (i, tally) fixed binary;
declare (text, key) character (100) varying;
Line 2,075 ⟶ 2,939:
end;
put skip list (tally);
end cnt;</
Output for the two specified strings is as expected.
Line 2,084 ⟶ 2,948:
7
</pre>
=={{header|PL/M}}==
<syntaxhighlight lang="plm">100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0, 0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;
/* PRINT A NUMBER */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (8) BYTE INITIAL ('.....',13,10,'$');
DECLARE (P, N) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
/* COUNT OCCURRENCES OF SUBSTRING IN STRING */
COUNT$SUBSTRING: PROCEDURE (STR, MATCH) ADDRESS;
DECLARE (STR, MATCH) ADDRESS, C BASED STR BYTE;
DECLARE (SP, MP) ADDRESS, (SC BASED SP, MC BASED MP) BYTE;
DECLARE COUNT ADDRESS;
COUNT = 0;
DO WHILE C <> '$';
SP = STR;
MP = MATCH;
DO WHILE SC = MC;
SP = SP + 1;
MP = MP + 1;
END;
IF MC = '$' THEN DO;
STR = SP;
COUNT = COUNT + 1;
END;
ELSE DO;
STR = STR + 1;
END;
END;
RETURN COUNT;
END COUNT$SUBSTRING;
CALL PRINT$NUMBER(COUNT$SUBSTRING(.'THE THREE TRUTHS$', .'TH$')); /* PRINTS 3 */
CALL PRINT$NUMBER(COUNT$SUBSTRING(.'ABABABABAB$', .'ABAB$')); /* PRINTS 2 */
CALL PRINT$NUMBER(COUNT$SUBSTRING(.'CAT$', .'DOG$')); /* PRINTS 0 */
CALL EXIT;
EOF</syntaxhighlight>
{{out}}
<pre>3
2
0</pre>
=={{header|PowerBASIC}}==
Line 2,095 ⟶ 3,014:
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.)
<
PRINT "the three truths, th:", TALLY("the three truths", "th")
PRINT "ababababab, abab:", TALLY("ababababab", "abab")
END FUNCTION</
{{out}}
Line 2,107 ⟶ 3,026:
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
[regex]::Matches("the three truths", "th").count
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 2,115 ⟶ 3,034:
</pre>
<syntaxhighlight lang="powershell">
[regex]::Matches("ababababab","abab").count
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 2,129 ⟶ 3,048:
Using SWI-Prolog's string facilities (this solution is very similar to the Logtalk solution that uses sub_atom/5):
<
count_substring(String, Sub, Total) :-
Line 2,147 ⟶ 3,066:
DropN is Before + Length,
sub_string(String, DropN, Remain, 0, Rest).
</syntaxhighlight>
Usage:
<
?- count_substring("the three truths","th",X).
X = 3.
Line 2,156 ⟶ 3,075:
?- count_substring("ababababab","abab",X).
X = 2.
</syntaxhighlight>
=== version using DCG ===
{{works with|SWI-Prolog|7.6.4}}
<
:- system:set_prolog_flag(double_quotes,chars) .
Line 2,195 ⟶ 3,114:
.
</syntaxhighlight>
{{out}}
Line 2,218 ⟶ 3,137:
=={{header|PureBasic}}==
<
b = CountString("ababababab","abab")
; a = 3
; b = 2</
=={{header|Python}}==
<
3
>>> "ababababab".count("abab")
2</
=={{header|Quackery}}==
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.
<syntaxhighlight lang="quackery"> [ [] 95 times
[ i^ space +
join ] ] constant is alphabet ( --> $ )
[ [ 2dup != while
-1 split drop
swap 1 split
unrot drop again ]
drop size ] is overlap ( [ [ --> n )
[ temp put [] swap
alphabet witheach
[ over -1 poke
over overlap
dup temp share
= if negate
swap dip join ]
drop temp release ] is eachend ( [ n --> [ )
[ [] swap
dup temp put
size times
[ temp share
i 1+ split drop
temp share size eachend
nested swap join ]
temp release ] is buildfsm ( $ --> [ )
[ dup [] = iff -1
else
[ behead
dup carriage = if
[ drop space ]
space - ]
swap ] is nextcharn ( $ --> n $ )
[ swap dup size
swap temp put
swap 0
[ over swap peek
temp take
nextcharn
temp put
dup 0 < iff
[ 2drop 0 ] done
peek
dup 0 < until ]
nip
temp take size - + ] is usefsm ( $ [ --> n )
[ over size 0 = iff
[ 2drop 0 ]
else
[ swap buildfsm
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.)
<syntaxhighlight lang="quackery"> [ over size 0 = iff
[ 2drop [] ] done
[] unrot
swap buildfsm
[ 2dup usefsm
rot 2dup found while
dip [ over size + ]
dip
[ rot over join
unrot ]
swap split
nip swap again ]
2drop drop ] is findall$ ( $ $ --> [ )
</syntaxhighlight>
{{out}}
Testing <code>findall$</code> in the Quackery shell.
<pre>O> $ "th" $ "the three truths" tuck findall$
... witheach [ split swap echo$ cr ]
... echo$
...
th
e th
ree truth
s
Stack empty.
</pre>
Finally we can use <code>findall$</code> to fulfil the task requirements.
<syntaxhighlight lang="quackery"> [ swap findall$ size ] is occurences ( $ $ --> n )
$ "the three truths" $ "th" occurences echo cr
$ "ababababab" $ "abab" occurences echo cr
</syntaxhighlight>
{{out}}
<pre>3
2
</pre>
=={{header|R}}==
Line 2,233 ⟶ 3,258:
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.
<
{v = attr(gregexpr(needle, haystack, fixed = T)[[1]], "match.length")
if (identical(v, -1L)) 0 else length(v)}
print(count("hello", "l"))</
{{libheader|stringr}}
<
print(str_count("hello", fixed("l")))</
=={{header|Racket}}==
<
(define count-substring
(compose length regexp-match*))
</syntaxhighlight>
<
> (count-substring "th" "the three truths")
3
> (count-substring "abab" "ababababab")
2
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
say count-substring("the three truths", "th"); # 3
say count-substring("ababababab", "abab"); #
say count-substring(123123123, 12); # 3</
The <tt>
=={{header|Red}}==
<
count-
length? parse string [collect [some [keep substring to substring]]]
]
test-case-1: "the three truths"
test-case-2: "ababababab"
print [test-case-1 "-" count-occurrences test-case-1 "th"]
print [test-case-2 "-" count-occurrences test-case-2 "abab"]
</syntaxhighlight>
{{out}}
<pre>
</pre>
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Prout <Count ('th') 'the three truths'>>
<Prout <Count ('abab') 'abababab'>>;
};
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,318 ⟶ 3,340:
::::* too many arguments
::::* if '''start''' is a positive integer (when specified)
<
w=. /*max. width so far.*/
bag= 'the three truths' ; x= "th" ; call showResult
Line 2,346 ⟶ 3,368:
if x=='' then x= " (null)" /* " " " " */
say left(bag, w) left(x, w%2) center(countstr(bag, x), 5)
return</
'''output''' when using the default (internal) inputs:
<pre>
Line 2,363 ⟶ 3,385:
=={{header|Ring}}==
<syntaxhighlight lang="ring">
aString = "Ring Welcome Ring to the Ring Ring Programming Ring Language Ring"
bString = "Ring"
Line 2,374 ⟶ 3,396:
cString = substr(cString,substr(cString,dString)+len(string(sum)))
end
return sum</
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}}==
<
str.scan(subStr).length
end
p countSubstrings "the three truths", "th" #=> 3
p countSubstrings "ababababab", "abab" #=> 2</
String#scan returns an array of substrings, and Array#length (or Array#size) counts them.
=={{header|Run BASIC}}==
<
print countSubstring("ababababab","abab")
Line 2,400 ⟶ 3,443:
i = instr(s$,find$,i) + len(find$)
WEND
END FUNCTION</
{{out}}
<pre>3
Line 2,406 ⟶ 3,449:
=={{header|Rust}}==
<syntaxhighlight lang="rust">
fn main() {
println!("{}","the three truths".matches("th").count());
println!("{}","ababababab".matches("abab").count());
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,420 ⟶ 3,463:
=={{header|Scala}}==
===Using Recursion===
<
def countSubstring(str1:String, str2:String):Int={
@tailrec def count(pos:Int, c:Int):Int={
Line 2,427 ⟶ 3,470:
}
count(0,0)
}</
===Using Sliding===
<
str.sliding(sub.length).count(_ == sub)</
===Using Regular Expressions===
<
<br/>
<
println(countSubstring("the three truths", "th"))</
{{out}}
<pre>2
Line 2,444 ⟶ 3,487:
=={{header|Scheme}}==
{{works with|Gauche Scheme}}
<
#<undef>
gosh> (length (lrxmatch "th" "the three truths"))
Line 2,450 ⟶ 3,493:
gosh> (length (lrxmatch "abab" "ababababab"))
2
</syntaxhighlight>
=={{header|Seed7}}==
<
const func integer: countSubstring (in string: stri, in string: searched) is func
Line 2,472 ⟶ 3,515:
writeln(countSubstring("the three truths", "th"));
writeln(countSubstring("ababababab", "abab"));
end func;</
{{out}}
Line 2,479 ⟶ 3,522:
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:'''
<
put the number of occurrences of "th" in "the three truths" --> 3
put the number of occurrences of "abab" in "ababababab" -- > 2
</syntaxhighlight>
'''User-created function:'''
<
put countSubstring("aaaaa","a") // 5
put countSubstring("abababa","aba") // 2
Line 2,494 ⟶ 3,558:
return number of occurrences of subString in mainString
end countSubstring
</syntaxhighlight>
=={{header|Sidef}}==
'''Built-in:'''
<
say "ababababab".count("abab");</
'''User-created function:'''
<
var re = Regex.new(ss.escape, 'g'); # 'g' for global
var counter = 0;
Line 2,510 ⟶ 3,574:
say countSubstring("the three truths","th");
say countSubstring("ababababab","abab");</
{{out}}
<pre>
Line 2,517 ⟶ 3,581:
</pre>
=={{header|Simula}}==
<
INTEGER PROCEDURE COUNTSUBSTRING(T,TSUB); TEXT T,TSUB;
Line 2,536 ⟶ 3,600:
OUTINT(COUNTSUBSTRING("ABABABABAB", "ABAB"),0);
OUTIMAGE;
END.</
{{out}}
<pre>
Line 2,545 ⟶ 3,609:
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<
Transcript showCR:('ababababab' occurrencesOfString:'abab')</
{{out}}
<pre>3
Line 2,552 ⟶ 3,616:
=={{header|SNOBOL4}}==
<syntaxhighlight lang="snobol4">
DEFINE("countSubstring(t,s)")
Line 2,564 ⟶ 3,628:
3
2
</syntaxhighlight>
=={{header|Standard ML}}==
<
let
fun aux (str', count) =
Line 2,585 ⟶ 3,649:
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");</
=={{header|Stata}}==
<
n = 0
k = 1-(i=strlen(x))
Line 2,601 ⟶ 3,665:
strcount("ababababab","abab")
2</
=={{header|Swift}}==
<
func countSubstring(str: String, substring: String) -> Int {
Line 2,612 ⟶ 3,676:
print(countSubstring(str: "the three truths", substring: "th"))
print(countSubstring(str: "ababababab", substring: "abab"))</
{{out}}
Line 2,621 ⟶ 3,685:
=={{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:
<
regexp -all ***=$needle $haystack
}
puts [countSubstrings "the three truths" "th"]
puts [countSubstrings "ababababab" "abab"]
puts [countSubstrings "abaabba*bbaba*bbab" "a*b"]</
{{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}}==
<
$$ MODE TUSCRIPT, {}
occurences=COUNT ("the three truths", ":th:")
occurences=COUNT ("ababababab", ":abab:")
occurences=COUNT ("abaabba*bbaba*bbab",":a\*b:")
</syntaxhighlight>
{{out}}
<pre>
Line 2,648 ⟶ 3,732:
=={{header|TXR}}==
<
@(do (defun count-occurrences (haystack needle)
(for* ((occurrences 0)
Line 2,661 ⟶ 3,745:
@(output)
@(count-occurrences hay ndl) occurrences(s) of @ndl inside @hay
@(end)</
<pre>$ ./txr count-occurrences.txr "baba" "babababa"
Line 2,668 ⟶ 3,752:
2 occurence(s) of cat inside catapultcatalog</pre>
=={{header|Uiua}}==
<syntaxhighlight lang="uiua">
F ← /↥⦷:
F "the three truths" "th"
F "ababababab" "abab"
</syntaxhighlight>
{{out}}
<pre>
3
2
</pre>
=={{header|UNIX Shell}}==
{{works with|Bash}}
<
function countString(){
Line 2,684 ⟶ 3,780:
countString "the three truths" "th"
countString "ababababab" "abab"</
{{Out}}
<pre>3
Line 2,691 ⟶ 3,787:
=={{header|VBA}}==
<
CountStringInString = UBound(Split(stLookIn, stLookFor))
End Function</
=={{header|VBScript}}==
'''user created function'''
<syntaxhighlight lang="vb">
Function CountSubstring(str,substr)
CountSubstring = 0
Line 2,713 ⟶ 3,810:
WScript.StdOut.Write CountSubstring("the three truths","th") & vbCrLf
WScript.StdOut.Write CountSubstring("ababababab","abab") & vbCrLf
</syntaxhighlight>
'''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 2,722 ⟶ 3,833:
=={{header|Visual Basic .NET}}==
<
Sub Main()
Console.WriteLine(CountSubstring("the three truths", "th"))
Line 2,741 ⟶ 3,852:
Return count
End Function
End Module</
{{Out}}
<pre>3
Line 2,747 ⟶ 3,858:
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}}==
<
c &[s t] #!s.match &(t)g
Line 2,756 ⟶ 3,879:
!!c "ababababab" "abab"
]]
}</
Returns: <pre>[3 2]</pre>
Line 2,762 ⟶ 3,885:
{{libheader|Wren-pattern}}
{{libheader|Wren-fmt}}
<
import "./fmt" for Fmt
var countSubstring = Fn.new { |str, sub|
Line 2,781 ⟶ 3,904:
var count = countSubstring.call(test[0], test[1])
Fmt.print("$6s occurs $d times in $q.", Fmt.q(test[1]), count, test[0])
}</
{{out}}
Line 2,791 ⟶ 3,914:
"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}}==
<
string 0; \use zero-terminated strings, instead of MSb terminated
Line 2,833 ⟶ 3,974:
[IntOut(0, SubStr("the three truths", "th")); CrLf(0);
IntOut(0, SubStr("ababababab", "abab")); CrLf(0);
]</
{{out}}
Line 2,854 ⟶ 3,995:
=={{header|zkl}}==
Two solutions:
<
while(Void!=(n:=s.find(p,n))){cnt+=1; n+=pn}
cnt
}</
{{trans|J}}
<
{{out}}
<pre>
Line 2,871 ⟶ 4,012:
=={{header|ZX Spectrum Basic}}==
<
20 LET t$="THE THREE TRUTHS": LET p$="TH": GO SUB 1000
30 STOP
Line 2,880 ⟶ 4,021:
1040 NEXT i
1050 PRINT p$;"=";c''
1060 RETURN </
|