📜  8086程序反向字符串

📅  最后修改于: 2021-06-28 15:40:35             🧑  作者: Mango

问题:给定一个字符串,我们必须反转该字符串并打印反转的字符串。

例子:

Input: String : "This is a sample string"
Output: gnirts elpmas a si sihT

Input: String : "Geeks for Geeks"
Output: skeeG rof skeeG 

解释:

  1. 创建一个字符串
  2. 遍历字符串
  3. 将字符推入堆栈
  4. 计算字符
  5. 加载字符串的起始地址
  6. 弹出堆栈的顶部字符,直到计数不等于零
  7. 放置字符并减少计数并增加地址
  8. 继续直到计数大于零
  9. 使用LEA命令在dx中加载字符串的有效地址
  10. 通过在AH中用9H调用中断来打印字符串
  11. 该字符串必须以“ $”符号结尾

程序:

.MODEL SMALL 
.STACK 100H 
.DATA 
  
; The string to be printed 
STRING DB 'This is a sample string', '$'
  
.CODE 
MAIN PROC FAR 
MOV AX,@DATA 
MOV DS,AX 
  
; call reverse function 
CALL REVERSE 
  
; load address of the string 
LEA DX,STRING 
  
; output the string
; loaded in dx 
MOV AH, 09H 
INT 21H 
  
; interrupt to exit
MOV AH, 4CH
INT 21H 
  
MAIN ENDP 
REVERSE PROC
    ; load the offset of
    ; the string 
    MOV SI, OFFSET STRING 
  
    ; count of characters of the; 
    ;string 
    MOV CX, 0H 
  
    LOOP1:
    ; compare if this is; 
    ;the last character 
    MOV AX, [SI] 
    CMP AL, '$'
    JE LABEL1 
  
    ; else push it in the; 
    ;stack 
    PUSH [SI] 
  
    ; increment the pointer; 
    ;and count 
    INC SI 
    INC CX 
  
    JMP LOOP1 
  
    LABEL1:
    ; again load the starting; 
    ;address of the string 
    MOV SI, OFFSET STRING 
  
        LOOP2: 
        ;if count not equal to zero 
        CMP CX,0 
        JE EXIT 
  
        ; pop the top of stack 
        POP DX 
  
        ; make dh, 0 
        XOR DH, DH 
  
        ; put the character of the; 
        ;reversed string 
        MOV [SI], DX 
  
        ; increment si and; 
        ;decrement count 
        INC SI 
        DEC CX 
  
        JMP LOOP2 
  
                  
    EXIT:
    ; add $ to the end of string 
    MOV [SI],'$ '
    RET 
          
REVERSE ENDP 
END MAIN 

输出:

gnirts elpmas a si sihT

笔记:
该程序无法在在线编辑器上运行,请使用MASM运行该程序,并使用dos框运行MASM,您可以使用任何8086仿真器运行该程序。