首页 > 解决方案 > 如何计算 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

此代码不比较/检查字符串的前两个字符。有人可以尽快帮助我吗?任何帮助将不胜感激。太感谢了。

标签: assemblyuser-inputx86-16emu8086

解决方案


字符串的读取和长度的计算工作正常。但是在比较字符串的字符时,它不适用于前两个字符。

碰巧,正是比较部分很好!你的烦恼从输入开始就存在,因为你不明白问号在汇编编程中的作用。

input db 10,?
length db ?
count db ?

在所有这些行中,问号? 表示大多数(如果不是全部)汇编程序将初始化为零值0的单个字节。你得到的是:

input  db 10, 0
length db 0
count  db 0

这对于lengthcount很好,但对于应该是 DOS 缓冲输入函数 0Ah 的输入缓冲区的输入则不然。您确实没有所需的存储空间。错误地覆盖了lengthcount等的内存!

解决办法是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

推荐阅读