SCASB compares AL with the byte at ES:DI. With REPNE it goes on while the bytes are different, so it stops at the first byte that equals AL, or when CX runs out.
What to build
Read a line of text, then a letter. Print the position of the first place where the letter appears in the text, counting from 1, or 0 if it does not appear.
Requirements
- The text is on the first line and the letter on the second.
- Search with REPNE SCASB.
- Print the position in decimal without leading zeros.
Input
A line of 1 to 30 characters, then Enter, then one character, then Enter.
Output
One number from 0 to 30.
Constraints
The text has no $. The letter is any character.
Example
Input:
hello
l
Output:
3
Why it works
After REPNE SCASB, CX holds how many bytes were left, including the match counted already, so the number of bytes examined is the length minus CX, and that is the position of the match counting from 1. The ZF flag tells the two stopping reasons apart: ZF = 1 means a match, and ZF = 0 means the whole text was scanned with no match.
Examples
hello l
3
assembly z
0
Hints
Hint 1
Read the first line with AH = 1, storing each key with STOSB (AL goes to ES:DI) and counting them in BX, until Enter.
Hint 2
Read the letter to search for. Then set DI to the start of the text, CX to the length, and use REPNE SCASB.
Hint 3
If ZF = 1 afterwards the letter was found, and the position (from 1) is the length minus CX. If it was not found, print 0.
Solution
Show one correct solution (try it yourself first)
; Where is the letter?
.MODEL SMALL
.STACK 100H
.DATA
TEXT DB 32 DUP(?)
.CODE
MAIN PROC
MOV AX, @DATA
MOV DS, AX
MOV ES, AX
CLD
LEA DI, TEXT
MOV BX, 0 ; the length
READ:
MOV AH, 1
INT 21H
CMP AL, 0DH
JE READY
STOSB ; store the key at ES:DI
INC BX
JMP READ
READY:
MOV AH, 1
INT 21H ; the letter to find
LEA DI, TEXT
MOV CX, BX
REPNE SCASB ; stop at the first byte equal to AL
JNE MISSING
MOV AX, BX
SUB AX, CX ; the position, counting from 1
JMP SHOW
MISSING:
MOV AX, 0
SHOW:
AAM ; AH = tens, AL = ones
MOV BX, AX
CMP BH, 0
JE ONES
MOV DL, BH
ADD DL, '0'
MOV AH, 2
INT 21H
ONES:
MOV DL, BL
ADD DL, '0'
MOV AH, 2
INT 21H
MOV AH, 4CH
INT 21H
MAIN ENDP
END MAIN
▶ Open this solution in the compiler, then press Visualize to watch it run step by step