Home > OS >  How to compare 2 characters of a string in assembler?
How to compare 2 characters of a string in assembler?

Time:12-12

I am trying to write a program where a string with words is entered. Then we enter the word to be deleted. In a loop, I'm trying to compare the characters of the first and second string, however the condition keeps returning positive always

I am using emulator emu8086

name test
.model small
.stack 100h
.data       
    wrd_ask db "word: $" 
    string_ask db "string: $"
    
    w_buffer db 255           
    wrd db 256 dup('$')
    
    s_buffer db 255    
    string db 256 dup('$')
.code

macro convert buffer
    push ax
    push dx
    lea dx, buffer
    mov ah, 0Ah
    int 21h 
    pop dx
    pop ax
endm

start: 
    mov ax, @data
    mov ds, ax
    
    mov dx, offset string_ask
    mov ah, 09h
    int 21h
    convert s_buffer
    
    mov dx, offset wrd_ask
    mov ah, 09h
    int 21h
    convert w_buffer
    
    mov si, 0
    mov di, 0  
    mov cx, 255
     
cycle:  
    inc si                
    inc di
    cmp string[si], wrd[di]
    je same

    same:
        mov dl, wrd[di]
        mov ah, 02h
        int 21h  
    
    LOOP cycle
end start

CodePudding user response:

cmp string[si], wrd[di]

You can't compare two memory bytes like that. The instruction set does not allow it. You need to load one of them in a register before comparing with the other:

mov  al, string[si]
cmp  al, wrd[di]
je same

same:

You need something in between here (whatever you want in case of 'not equal'). Else, regardless of the outcome of the comparison, will the code at same get executed.


Try the following:

cycle:  
    inc  si                
    inc  di
    mov  dl, string[si]
    cmp  dl, wrd[di]
    jne  different
    mov  ah, 02h
    int  21h  
    loop cycle
same:
    ...
    mov  ax, 4C00h
    int  21h
different:
    ...
    mov  ax, 4C00h
    int  21h

Use the sentence: "stackoverflow rocks"
Use the word: "stackunderflow"

Observe the result "stack" (the first difference is between "o" and "u".

  • Related