Reputation: 21
how can I reverse a string letter by letter and compare it with the first string letter by letter using SI? I originally thought about adding SI to Cl for the loop but found that it won't let me add SI to Cl. Any suggestions would be greatly appreciated. This is the code that I used and just used the same string to test the comparison.
.model small
.stack 100h
.data
input db 'Input string: $'
display db 10,10,13,'String is $'
length db 10,10,13,'String length is $'
character db 10,10,13,'Characters are:$'
equaldata db 'Equal$'
notequaldata db 'Not Equal$'
string db 20 dup('$')
.code
mov ax, @data
mov ds, ax
lea si, string
mov ah, 09h
mov dx, offset input
int 21h
mov ah, 0Ah ;request to input string
lea dx, string
int 21h
mov ah, 09h
mov dx, offset display
int 21h
lea dx, string + 2
int 21h
mov ah, 09h
mov dx, offset length
int 21h
mov bl, string + 1 ;length of string
mov ax, 0
mov al, bl ;length in hexadecimal
aam ;length in decimal
mov ch, ah ;tens digit of length
mov cl, al ;ones digit of length
mov ah, 02h
add ch, 30h
mov dl, ch ;display tens digit of length
int 21h
add cl, 30h
mov dl, cl ;display ones digit of length
int 21h
mov ah, 09h
mov dx, offset character
int 21h
mov cx, 0
mov cl, bl ;counter for loop
mov dh, cl
print_character:
mov bh, si + 2
mov ah, 02h
mov dl, 0Ah ;newline
int 21h
mov dl, 0Dh ;carriage return
int 21h
mov dl, bh ;character of string
int 21h
mov dl, 20h ;spaces
int 21h
int 21h
int 21h
int 21h
;----------------------second letter--------------
mov bl, si + 2
mov dl, bl
int 21h
mov dl, 20h
int 21h
int 21h
int 21h
int 21h
;---------------------equal or not equal-----------
cmp bh, bl
je equal
jne notequal
equal:
mov ah, 09h
mov dx, offset equaldata ;display equal data
int 21h
jmp lineend
notequal:
mov ah, 09h
mov dx, offset notequaldata ;display not equal
int 21h
jmp lineend
lineend:
inc si
dec dh
loop print_character
int 20h
end
Upvotes: 2
Views: 304
Reputation: 39205
reverse a string letter by letter and compare it with the first string letter by letter
This is pretty useless because only in the case of a palindrome the compare will result in equality. Testing for a palindrome doesn't need reversing at all! Use 2 pointers, one at the start of the string, one at te end of the string. Stop at the first inequality. If you arrive in the middle, you know the string is a palindrome.
Since you've got the string length in BL, this code will setup for the loop:
mov bh, 0
dec bx
lea di, [si+2]
Again:
mov al, [di] ;Character from the front of the string
mov ah, [di+bx] ;Character from the rear of the string
cmp al, ah
...
inc di
sub bx, 2
jnbe Again
IsPalindrome:
In your current code you inevitably get equality since you compare identical memory content.
print_character:
mov bh, si + 2
...
;----------------------second letter--------------
mov bl, si + 2
...
;---------------------equal or not equal-----------
cmp bh, bl
je equal
jne notequal
Upvotes: 1