'===========================================================================
' Subject: COUNT ALL INSTANCES OF A CHAR      Date: 01-28-97 (19:59)       
'  Author: Brian Mclaughlin                   Code: ASM                    
'  Origin: comp.lang.basic.misc             Packet: ASMCODE.ABC
'===========================================================================
; CHARCNT.ASM  - assemble with MASM 5.1 or compatible assembler
;              - for use with QB4.x / PDS near strings only
;              - written by Brian McLaughlin. Released to public domain.
;
; This FUNCTION is designed to count all instances of a character
; in a string. The character to be counted is passed to the routine
; as an ASCII code.
;
; Declare it:   DECLARE FUNCTION CharCount% (St$, Char%)
;
; Example:   Test$ = "000X000X00"
;            PRINT CharCount% (Test$, ASC("X"))  'prints 2

.MODEL MEDIUM, BASIC
.CODE

CharCount PROC USES ES DI SI, String:WORD, Char:WORD
        Push DS                 ; We need to set ES = DS
        Pop ES                  ; so we'll use the stack to do it
        Cld                     ; make certain of forward scan
        Mov BX, String          ; the address of descriptor
        Mov CX, [BX]            ; CX = length of string
        Mov DI, [BX+2]          ; ES:DI = address of first byte of String
        Mov BX, Char            ; the address of Char
        Mov AL, Byte Ptr [BX]   ; AL = character to count
        Xor DX, DX              ; start count at zero
Top:
        Jcxz Exit               ; exit if it's a null string
        Repne Scasb             ; scan for the count char (in AL)
        Jnz Exit                ; zero flag clear if no match found
        Inc DX                  ; DX accumulates the count
        Jmp SHORT Top
Exit:
        Mov AX, DX
        Ret

CharCount ENDP
          END
