在 Assembly 中反转输入字符串

Reversing an input string in Assembly

我有这个汇编代码可以反转我输入的字符串。它最多只接受 20 个字符。我的问题是,当我按回车键查看输出时,反转字符串的末尾有一个额外的字符。
请帮助我理解为什么会发生这种情况以及如何在输出中删除它。
我们只需要使用函数 09H int 21h 来显示字符串和函数 0Ah int 21h 来输入字符串。我们正在使用 TASM。
非常感谢您的帮助。谢谢。

这是我的代码:

.model small
.stack 100h
.data 
    MSG DB "Input String(max 20 chars): ", 10, 13, "$"
    Sentence1 DB 21,?,21 dup("$")  
    str2 dw 21 dup("$")
.code
start:
    mov ax, @data
    mov ds, ax

    ;Getting the string input
        mov ah,09h
        lea dx, MSG
        int 21h

        lea si,Sentence1
        mov ah,0ah
        mov dx,si
        int 21h

    ;Reverse String    
        mov cl,Sentence1
        add cl,1
        add si,2
    loop1:
        inc si
        cmp byte ptr[si],"$"
        jne loop1

        dec si
        lea di,str2
    loop2:
        mov al,byte ptr[si]
        mov byte ptr[di],al
        dec si
        inc di
        loop loop2

        ;Printing the reverse string    
            mov ah,09h
            lea dx,str2
            int 21h    

        mov ah, 4ch
        int 21h
end start 
str2 dw 21 dup("$")

通常这会使用 db 指令。


mov cl,Sentence1
add cl,1

反转循环使用CX作为它的循环计数器,但你没有设置正确!
"Sentence1" 输入结构的第 2 个字节包含您想要在 CX 寄存器中的值。您无需搜索任何终止字符。此外,如果您这样做了,您宁愿寻找 ASCII 代码 13(回车 return)而不是“$”。

mov cl, [si + 1]   ;Number of characters in the string
mov ch, 0          ;Make it a word because LOOP depends on CX (not just CL)

设置SI然后变成:

add si, 2          ;To the start of the string
add si, cx         ;To the position after the string
dec si             ;To the last character of the string

但更短:

add si, cx
inc si

如果用户没有输入任何文本,您将希望完全绕过反转!这就是下一个代码中 jcxz 的用途:

 lea si, Sentence1
 mov ah, 0Ah
 mov dx, si
 int 21h

 ;Reverse String    
 mov cl, [si + 1]
 mov ch, 0
 add si, cx
 inc si
 lea di, str2

 jcxz EmptyString     ;By-pass the reversal entirely!

loop2:
 mov al, byte ptr[si]
 mov byte ptr[di], al
 dec si
 inc di
 loop loop2

EmptyString:
 ;Printing the reverse string (could be empty)
 mov ah, 09h
 lea dx, str2
 int 21h