實驗2:(子字符串,查找字符串在另一個字符串中出現的位置)
設計算法:將用戶輸入關鍵字和句子,將bx爲關鍵字起始位置地址,dx賦初值爲句子起始位置地址,將dx和bx內容進行匹配,如果不匹配則dx指向句子下一個字符及inc dx。用di表示當字符匹配成功時bx,dx的偏移量,di賦初值爲0,[bx+di]與[dx+di]比較,如果匹配成功di自增1,直到di加到等於關鍵字長度時顯示結果匹配成功,如果中間有匹配不成功di重置爲0,直到當整個句子查詢完沒匹配則顯示結果不匹配.
程序實現:調用print子程序,將緩衝區字符串顯示出來,調用cin子程序將用戶輸入字符串存入指定緩衝區。另 cx=句子長度,用bx,dx分別等於關鍵字地址和句子地址按照前面所說的算法來編程。此外,還有一個要求需要顯示當匹配成功時的子字符串位置:匹配的位置等於句子長度-cx,或匹配位置=dx-句子首地址,調用數字輸出子程序。要注意的是:得出來的結果爲十進制數字,要想以十六進制格式輸出數字還需要將其轉化成ASCII輸出.
十六進制數字輸出算法;(在附錄中會附上十進制數輸出代碼)具體思路:將數字除以16,將餘數壓入棧中,商繼續除以16,得出來的餘數再壓入棧中,
重複上述步驟,直到商爲0時結束,再將棧頂元素依次推出並輸出(判斷是否小於10,小於10加30H輸出,大於10加31h輸出)。
DATAS SEGMENT
;此處輸入數據段代碼
msg db 'enter keyword:$'
msg1 db 'enter sentence:$'
msg2 db 'NoMatch$'
msg3 db 'last Match location at:$'
keepcin db 100
cinlen db 0
cinfld db 100 dup(0)
keepcin1 db 100
cin1len db 0
cin1fld db 100 dup(0)
DATAS ENDS
STACKS SEGMENT
;此處輸入堆棧段代碼
STACKS ENDS
CODES SEGMENT
ASSUME CS:CODES,DS:DATAS,SS:STACKS
START:
MOV AX,DATAS
MOV DS,AX
mov es,ax
;此處輸入代碼段代碼
;此處爲標題輸出和輸入
mov dx,offset msg
call print ;"enter keyword"
mov dx,offset keepcin
call cin
mov dx,offset msg1
call print
mov dx,offset keepcin1
call cin
;用戶輸入完成接下來要完成字符串匹配
mov bx,offset cinfld ;關鍵字
mov dx,offset cin1fld ;句子
mov cl,cin1len ;循環次數爲句子長度
mat:
call comparestr
cmp al,0
je match
inc dx
loop mat
jmp noMatch ;遍歷完都沒找到
match:
mov dx,offset msg3
call print
mov al,cin1len
sub al,cl
mov dl,al ;索引從0開始
call dispdec
jmp stop
noMatch: ;沒有查詢到結果
mov dx,offset msg2
call print
stop:
MOV AH,4CH
INT 21H
;以下爲子程序
comparestr proc ;dx,bx指向字符串,比較字符串大小,相等爲al=0,否則-1
push cx
push si
push di
mov si,dx
mov di,bx ;
mov cl,cinlen ;改成字符串長度
cld
lastagain: cmpsb
jnz lastunmat
loop lastagain
;匹配成功
mov al,0
jmp lastoutput
lastunmat: mov al,-1
lastoutput:
pop di
pop si
pop cx
ret
comparestr endp
;打印固定字符串
print proc
push ax
mov ah,09h
int 21h
pop ax
ret
print endp
;十進制輸出,入口參數dx
dispdec proc
push ax
push bx
push cx
push dx
mov ax,dx
xor dx,dx
mov bx,10
mov cx,0
a:
cmp ax,10
jb ok
div bx
add dl,30h
push dx
xor dx,dx
inc cx
jmp a
ok:
add al,30h
push ax
inc cx
b:
pop dx
mov ah,2
int 21h
loop b
pop dx
pop cx
pop bx
pop ax
ret
dispdec endp
;用戶輸入
cin proc
push ax
mov ah,0AH
int 21h
pop ax
call printnewline
ret
cin endp
;輸出換行
printnewline proc
push ax
push dx
mov ah,02h
mov dl,0dh
int 21h
mov dl,0ah
int 21h
pop dx
pop ax
ret
printnewline endp
CODES ENDS
END START
輸出結果如圖: