我有一个即将完成的脚本,我正在努力完成单词计数器。我正在努力完成单词计数器。在这种情况下,我正在计算每个空格的实例,并假设它意味着一个单词的结束。
'totalWords'变量初始化为0,并且每次在字符串中发现''时都会递增。
然而,每次测试时,输出总是'+0'。我知道脚本的其他部分是可以工作的,因为它成功地转换了字母的大小写。
递增一个变量并显示它的最佳做法是什么?
INCLUDE Irvine32.inc
.data
source BYTE 40 DUP (0)
byteCount DWORD ?
target BYTE SIZEOF source DUP('#')
sentencePrompt BYTE "Please enter a sentence: ",0
wordCountPrompt BYTE "The number of words in the input string is: ",0
outputStringPrompt BYTE "The output string is: ",0
totalWords DWORD 0 ; SET TOTALWORDS VARIABLE TO 0 INITIALLY
one DWORD 1
space BYTE " ",0
.code
main PROC
mov edx, OFFSET sentencePrompt
call Crlf
call WriteString
mov edx, OFFSET source
MOV ecx, SIZEOF source
call ReadString
call Crlf
call Crlf
call TRANSFORM_STRING
call Crlf
exit
main ENDP
TRANSFORM_STRING PROC
mov esi,0
mov edi,0
mov ecx, SIZEOF source
transformStringLoop:
mov al, source[esi]
.IF(al == space)
inc totalWords ; INCREMENT TOTALWORDS DATA
mov target[edi], al
inc esi
inc edi
.ELSE
.IF(al >= 64) && (al <=90)
add al,32
mov target[edi], al
inc esi
inc edi
.ELSEIF (al >= 97) && (al <=122)
sub al,32
mov target[edi], al
inc esi
inc edi
.ELSE
mov target[edi], al
inc esi
inc edi
.ENDIF
.ENDIF
loop transformStringLoop
mov edx, OFFSET wordCountPrompt
call WriteString
mov edx, OFFSET totalWords ; DISPLAY TOTALWORDS
call WriteInt
call Crlf
mov edx, OFFSET outputStringPrompt
call WriteString
mov edx, OFFSET target
call WriteString
ret
TRANSFORM_STRING ENDP
END main
这一部分是不正确的。
mov edx, OFFSET totalWords ; DISPLAY TOTALWORDS
call WriteInt
WriteInt
不期望有偏移 edx
中的实际整数值;它希望在 eax
. 所以代码应该是这样的。
mov eax, totalWords ; DISPLAY TOTALWORDS
call WriteInt
还有,你的空格变量是没有意义的 你可以直接写
.IF(al == ' ')
而你的数词方式听起来有点破。一个字符串,如 "foo bar"
只包含1个空格,但有两个字。请注意,你不能真正使用 number_of_spaces+1
也不是,因为这将会给类似于 " "
, "foo bar"
和 "foo "
.
你可能会得到更好的结果,像。
if (al != ' ' && (esi == 0 || source[esi-1] == ' ')) totalWords++;
这只是一些伪代码来表达这个想法. 我让你把它翻译成x86汇编。