CMPSB compares the byte at DS:SI with the byte at ES:DI. With REPE it goes on while the bytes are equal, so it stops at the first difference, or when CX runs out.
What to build
Read two lines and tell whether they are the same. If they are not, say where they first differ.
Requirements
- Print
equalwhen both lines are identical. - Print
different lengthwhen the lines have different lengths. - Otherwise print
differ atand the position (from 1) of the first character that is different.
Input
Two lines of 1 to 20 characters each, each ended by Enter.
Output
One line, as described.
Constraints
The lines do not contain $.
Example
Input:
apple
apple
Output:
equal
Why it works
REPE CMPSB repeats while the pair of bytes is equal, and it stops after the first pair that is different, having already counted it. So the number of pairs examined is the length minus CX, and the last of them is the position of the difference. ZF tells why it stopped: 1 for the end of the count with every pair equal, 0 for a difference.
Examples
apple apple
equal
apple apply
differ at 5
Hints
Hint 1
Write a procedure READLINE that reads keys until Enter, stores them with STOSB at ES:DI and returns the length in CX. Call it for each buffer.
Hint 2
If the two lengths differ, print `different length`. Otherwise set SI and DI to the two buffers, CX to the length, and use REPE CMPSB.
Hint 3
After REPE CMPSB, ZF = 1 means all bytes matched (print `equal`). If ZF = 0 the first difference is at position length minus CX, counting from 1.
Solution
Show one correct solution (try it yourself first)
; Compare two lines
.MODEL SMALL
.STACK 100H
.DATA
LINE1 DB 24 DUP(?)
LINE2 DB 24 DUP(?)
EQ DB 'equal$'
DLEN DB 'different length$'
AT DB 'differ at $'
.CODE
MAIN PROC
MOV AX, @DATA
MOV DS, AX
MOV ES, AX
CLD
LEA DI, LINE1
CALL READLINE
MOV BX, CX ; the first length
LEA DI, LINE2
CALL READLINE ; CX = the second length
CMP BX, CX
JNE LENGTHS
LEA SI, LINE1
LEA DI, LINE2
MOV CX, BX
REPE CMPSB ; compare while equal
JE SAME
LEA DX, AT
MOV AH, 9
INT 21H
MOV AX, BX
SUB AX, CX ; the position of the difference, from 1
AAM
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
JMP DONE
LENGTHS:
LEA DX, DLEN
JMP SHOW
SAME:
LEA DX, EQ
SHOW:
MOV AH, 9
INT 21H
DONE:
MOV AH, 4CH
INT 21H
MAIN ENDP
READLINE PROC ; stores a line at ES:DI; returns the length in CX
MOV CX, 0
KEY:
MOV AH, 1
INT 21H
CMP AL, 0DH
JE FINISHED
STOSB
INC CX
JMP KEY
FINISHED:
RET
READLINE ENDP
END MAIN
▶ Open this solution in the compiler, then press Visualize to watch it run step by step