assembly - 如何计算 8086 ALP 中字符串中元音的数量?
问题描述
我编写了一个汇编程序,它计算用户读取的字符串中元音的数量。字符串的读取和长度的计算工作正常。但是在比较字符串的字符时,前两个字符不起作用。这是我的代码。
.MODEL small
.STACK
.DATA
input db 10,?
length db ?
count db ?
.CODE
.STARTUP
;reading string
mov dx,00h
mov dx,offset input
mov ah,0Ah
int 21h
;calculating length
mov length,00h
mov si,offset input+2
;checking for vowels
loopi: cmp [si],'$'
je next
add length,01h
inc si
loop loopi
next:
mov cx,00h
mov cl,length
mov si,offset input+2
mov count,00h
counting:cmp [si],'a'
je count1
cmp [si],'e'
je count1
cmp [si],'i'
je count1
cmp [si],'o'
je count1
cmp [si],'u'
je count1
inc si
loop counting
cmp cl,00h
je exit
count1:inc count
inc si
loop counting
exit:
.EXIT
end
此代码不比较/检查字符串的前两个字符。有人可以尽快帮助我吗?任何帮助将不胜感激。太感谢了。
解决方案
字符串的读取和长度的计算工作正常。但是在比较字符串的字符时,它不适用于前两个字符。
碰巧,正是比较部分很好!你的烦恼从输入开始就存在,因为你不明白问号在汇编编程中的作用。
input db 10,? length db ? count db ?
在所有这些行中,问号? 表示大多数(如果不是全部)汇编程序将初始化为零值0的单个字节。你得到的是:
input db 10, 0
length db 0
count db 0
这对于length和count很好,但对于应该是 DOS 缓冲输入函数 0Ah 的输入缓冲区的输入则不然。您确实没有所需的存储空间。错误地覆盖了length、count等的内存!
解决办法是input db 10, 0, 10 dup (?)
。这允许输入 9 个字符。为什么是9?因为 DOS 总是将回车13附加到输入中,并且该回车还需要在由10 dup (?)
.
这个回车也解释了为什么你的长度计算会失败。当您应该搜索 ASCII 代码 13 时,您正在搜索“$”。
当然计算长度是多余的,因为 DOS 已经通知你了。输入结构的第二个字节是长度。
mov cx, 0
mov cl, [input+1] ; length
全部一起:
.DATA
input db 10, 0, 10 dup (?)
count db ?
.CODE
.STARTUP
;reading string
mov dx, offset input
mov ah, 0Ah
int 21h
;checking for vowels
xor cx, cx ; Also clears the CX register like `mov cx, 0`
mov count, cl ; Count = 0
mov si, offset input+2
mov cl, [si-1] ; length is 2nd byte
counting:
cmp [si], 'a'
je count1
cmp [si], 'e'
je count1
cmp [si], 'i'
je count1
cmp [si], 'o'
je count1
cmp [si], 'u'
je count1
inc si
loop counting
cmp cl, 0 \ You can replace these 2 by
je exit / a single `jmp exit`
count1:
inc count
inc si
loop counting
exit:
.EXIT
更好的解决方案
- 不使用慢
loop
指令 - 最小化内存访问
- 使用字符串原语,如
lodsb
- 如果字符串为空,则不会失败!
- 尽量减少跳来跳去的次数
在这里介绍:
;checking for vowels
cld ; For completeness because `lodsb` depends on it
mov si, offset input+2
mov dl, -1
vowel:
inc dl
other:
lodsb ; This is `mov al, [si]` followed by `inc si`
cmp al, 'a'
je vowel
cmp al, 'e'
je vowel
cmp al, 'i'
je vowel
cmp al, 'o'
je vowel
cmp al, 'u'
je vowel
cmp al, 13
jne other
mov count, dl
推荐阅读
- java - JProgressBar 不会在 actionPerformed 内更新 - Java Swing
- python - 将嵌套的 json 转换为 csv,其中每一行包含最内层的值和所有父值
- java - 在 ActionListener 的 actionPerformed() 方法中暂停执行代码
- php - Facade\Ignition\Exceptions\ViewException 语法错误,文件意外结束
- javascript - 飞行气球动画
- python - 如何在 Django 模板中设置过滤器
- angular - RxJs / Ngrx 限制对指定参数的 http 调用
- azure - Azure 价格计算 - 从 Onprimises 到 Azure ASR DR 的 DR VM
- bash - 在 WSL 上从 Bash 打开 Sublime Text
- ssl-certificate - DocuSign API 返回异常:SSL 证书问题:证书链中的自签名证书