I'm trying to check if a certain char shows up in a string. If it does, I want to update a counter, then eventually print that counter.
For example, if my comparison char is "a", and I'm checking the string "haha", I should have a counter with the value 2.
From my understanding, we want to load the address of the string into a register, check the memory location (a Byte) at that address against a comparison char, then increment the address to look at the next Byte. And so on.
I've spent hours on this problem. I feel I'm on the right track (I hope), but a little guidance on how to (re-)think this problem would be wonderful.
My biggest issue, so far that I can understand, is comparing a single char from my string to my comparison char, which is "a". I'm struggling with the interaction rules, as it were, between registers -- what can be moved to what, and so on.
Thanks kindly for considering my question.
Here's my code so far:
SECTION .data ; Initialize data
cmp_char db "a", 0h
word1 db "harp", 0h
word2 db "haha" , 0h
SECTION .text
global _start ; Initialize starting point for program
_start: ; Program entry point
jmp check_for_vowel ; Jumps to "check_for_vowel" function
check_for_vowel:
push EDX ; Preserve EDX on the stack; restore after function runs
push ECX ; Preserve ECX on the stack; restore after function runs
push EBX ; Preserve EBX on the stack; restore after function runs
push EAX ; Preserve EAX on the stack; restore after function runs
mov EDX, 0 ; Initialize char counter
mov AH, [cmp_char] ; Load value of "cmp_char" into AH, an 8-bit subsection of EAX
mov EBX, word1 ; Move address of word1 to EBX.
loop_counter:
mov AL, Byte [EBX] ; Move value of BX into AL, an 8-bit subregister of EAX
cmp AL, 0h ; Check if value in AL is 0...
jz finished ; ... and if it is, jump to "finished" function.
cmp AL, AH ; Else, compare the Bytes in AL and AH...
jz match ; ... and if they match, jump to the "match" function.
inc ECX ; Otherwise, increment the loop counter...
inc EBX ; ... and loop to the next character in the string...
jmp loop_counter ; ... and start the loop over again.
match:
inc EDX ; Increment the char counter.
inc EBX ; Loop to the next character in the string.
jmp loop_counter ; Jump back to the loop_counter.
finished:
ret
Edit 1: fix -- incremented EBX under "loop_counter"; originally EX.