首页 > 代码库 > 汇编语言-比较字符串

汇编语言-比较字符串

 比较两个字符串

1. 题目:比较字符串是否相等

2. 要求:写一程序,比较两个字符串String1和String2所含的字符是否相同;若相同则显示’Match’,否则显示’No Match’。

输入两个字符串之后,将串操作所必须的寄存器等参数设置好,然后使用串操作指令进行从头到尾的比较,两个字符串相等的条件是串长度相等且对应的字符相同。

 1 ; Example assembly language program -- 
 2 ; Author: karllen
 3 ; Date:    revised 05/2014
 4 
 5 .386
 6 .MODEL FLAT
 7 
 8 ExitProcess PROTO NEAR32 stdcall, dwExitCode:DWORD
 9 
10 INCLUDE io.h            ; header file for input/output
11 
12 cr      EQU     0dh     ; carriage return character
13 Lf      EQU     0ah     ; line feed
14 
15 .STACK  4096            ; reserve 4096-byte stack
16 
17 .DATA     
18        str1    BYTE 80 DUP(?)
19        str2    BYTE 80 DUP(?)
20        value   BYTE 11 DUP(?)
21        length1 DWORD ?
22        length2 DWORD ?  
23        
24        promot1 BYTE "Please Enter String1",cr,Lf,0
25        promot2 BYTE "Please Enter String2",cr,Lf,0
26        crlf    BYTE  cr,Lf,0
27        
28        answerYes BYTE "Match",cr,Lf,0
29        answerNo  BYTE "No Match",cr,Lf,0       
30 PUBLIC _start                   ; make entry point public       
31 .CODE                          ; start of main program code             
32 _start:
33        output promot1
34        input  str1,80
35        lea    eax,str1
36        push   eax
37        call   strlen
38        add    esp,4
39        mov    length1,eax
40        dtoa   value,eax
41        output value
42        output crlf
43        
44        output promot2
45        input  str2,80
46        lea    eax,str2
47        push   eax 
48        call   strlen   
49        add    esp,4  
50        mov    length2,eax
51        dtoa   value,eax
52        output value
53        output crlf
54        
55        mov  edx,length2
56        ;;cmp String1 and String2
57        cmp    eax,edx        ;如果长度不相等
58        jne    endCMP              ;则结束
59        ;比较
60        lea esi,str1
61        lea edi,str2
62        mov ecx,length2  ;比较的长度
63        repe cmpsb 
64        jz   found       ;比较成功则跳转
65       
66        endCMP:
67               output answerNo
68               jmp endMatch
69        found:
70               output answerYes
71         ;
72        endMatch:
73        
74         INVOKE  ExitProcess, 0  ; exit with return code 0
75 
76 strlen      PROC    NEAR32
77             push    ebp             
78             mov     ebp, esp
79                                        
80             sub     eax, eax        
81             mov     ebx, [ebp+8]    
82 whileChar:  cmp     BYTE PTR [ebx], 0  
83             je      endWhileChar   
84             inc     eax           
85             inc     ebx            
86             jmp     whileChar      
87 endWhileChar:
88             pop     ebp
89             ret               
90 strlen      ENDP
91 END                             ; end of source code