Count occurrences of a substring: Difference between revisions

Content deleted Content added
Not a robot (talk | contribs)
Add Cowgol
Not a robot (talk | contribs)
Add 8080 assembly
Line 108: Line 108:
ababababab abab 2
ababababab abab 2
</pre>
</pre>

=={{header|8080 Assembly}}==

The routine <code>subcnt</code> takes the string pointer in <code>HL</code>
and the substring pointer in <code>BC</code>, and returns a 16-bit count in
<code>DE</code>.

<lang 8080asm> org 100h
jmp demo
;;; Count non-overlapping substrings (BC) in string (HL)
;;; Returns amount of matches in DE
subcnt: lxi d,0 ; Amount of matches
s_scan: mov a,m ; Get current character
ana a ; End of string?
rz ; Then stop
push b ; Keep start of substring search
push h ; Keep current location in string
s_cmp: ldax b ; Get character from substring
cmp m ; Compare to curent charracter of search string
inx b ; Advance pointers
inx h
jz s_cmp ; Keep going if they were equal
ana a ; Did we reach the end of the substring?
jz s_find ; If so, we found a match
pop h ; Otherwise, no match - restore search position
pop b ; Restore start of substring
inx h ; Try next position
jmp s_scan
s_find: inx d ; We found a match
pop b ; Discard start of the search, keep going after match
pop b ; Restore start of substring
dcx h ; The comparison routine overshoots by one
jmp s_scan
;;; Test on a few strings
demo: lxi h,pairs
loop: mov e,m ; Load string pointer
inx h
mov d,m
inx h
mov a,d ; If 0, stop
ora e
rz
mov c,m ; Load substring pointer
inx h
mov b,m
inx h
push h ; Save example pointer
xchg ; Put string pointer in HL
call subcnt ; Count substrings
mvi a,'0' ; Assuming output is <10, print output
add e ; (This is true for all examples, and a proper numeric
mov e,a ; output routine is big and not relevant.)
mvi c,2 ; CP/M character output
call 5
pop h ; Restore example pointer
jmp loop
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</lang>

{{out}}

<pre>320</pre>


=={{header|Ada}}==
=={{header|Ada}}==