Counting all words in a given string
A program that counts the number of words in a given string.
Program source code
title .model small .stack 100h data segment public string db "I've got many friends in China$" strlen equ ($-string) output db "Number of words: $" count dw 0 data ends code segment public assume ds:data, cs:code main proc mov ax, seg data ; Get the data segment address and store it in ax mov ds, ax ; Pass the data segment address from ax to ds xor si, si ; Clear the si counter register mov cx, strlen ; Copy the value of the strlen variable into the cx register lea bx, ds:[string] ; Load the address of the string variable into the ds:bx register MainLoop: cmp byte ptr[bx+si-1], 20h ; Compare the value in bx at index si-1 with a space jne Skip ; If ZF=0, jump to the Skip label inc count ; Increment the count variable value by 1 Skip: inc si ; Increment the si index value by 1 loop MainLoop ; Loop while CX≠0 inc count ; Increment the count value by 1. Account for the last word mov ah, 09h ; Copy the string output function number into ah lea dx, ds:[output] ; Load the address of the output variable into the ds:dx register int 21h ; Call the interrupt mov dx, count ; Copy the value of the count variable into the dx register call PrintNumber ; Call the PrintNumber procedure (it is described in example 2: Counting all vowels in a string) mov ax, 4C00h ; Copy the termination function number into ah and the value into al int 21h ; Call the interrupt main endp code ends end main
Number of words: 6
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".