Menu
CoddyTech

Count the Words

Part of the Functions, Stack and Strings section of Coddy's Assembly journey. Lesson 30 of 33.

challenge icon

Challenge

Easy

Keep counting characters and lines. Also count the words: a word starts at a byte that is not a space (32) or a newline (10) when the byte before it is a space, a newline, or there is no byte before it. Print the number of words instead of the lines, then a newline.

Example: for the input hello world the program prints 2.

Write the whole program in main.asm. The locked lib.asm holds print_number and print_char.

Try it yourself

bits 64
extern print_number
extern print_char
section .bss
    buffer resb 4096
section .text
    global _start
_start:
    mov rax, 0
    mov rdi, 0
    mov rsi, buffer
    mov rdx, 4096
    syscall
    mov rbx, rax
    xor r12, r12
    xor r13, r13
    xor r14, r14
.next:
    cmp r12, rbx
    jge .done
    cmp byte [buffer + r12], 10
    je .newline
    inc r13
    jmp .after
.newline:
    inc r14
.after:
    inc r12
    jmp .next
.done:
    test rbx, rbx
    jz .report
    cmp byte [buffer + rbx - 1], 10
    je .report
    inc r14
.report:
    mov rdi, r14
    call print_number
    mov rdi, 10
    call print_char
    mov rax, 60
    mov rdi, 0
    syscall

All lessons in Functions, Stack and Strings

Practice on your own: Assembly playground