【发布时间】:2021-03-25 15:34:13
【问题描述】:
我在 A 中有字符串“Hello world”,我想知道有多少个单词组成了 A,我将这个数字保存在 D 中,如下图所示。我该怎么做?
A → “Hello World”
D → 2
【问题讨论】:
-
您还没有准确定义您认为算作“单词”的内容。也就是说,一个词在哪里开始和结束?一旦你决定了规则,编写一个循环遍历你的字符串并根据你的规则计算一个单词开始的次数。
我在 A 中有字符串“Hello world”,我想知道有多少个单词组成了 A,我将这个数字保存在 D 中,如下图所示。我该怎么做?
A → “Hello World”
D → 2
【问题讨论】:
.text
main:
# prompt user for string
la $a0 prompt
li $v0 4
syscall
# get string
la $a0 A
li $a1 50 # maximum size of string
li $v0 8
syscall
move $s0 $a0 # incrementable pointer to buf
li $s1,0
li $t3,0
loop:
# t1 = *(A++) and exit if '\0' or '\n'
lb $t1 ($s0) # t1 = *A
beqz $t1 end # break if '\0'
beq $t1 10 end # break if '\n'
add $s0,$s0,1
beq $t1,32,is_space # if current char is space jump to is_space
li $t3,1 # the current char isn't space so set $t3 to 1
j loop
is_space:
beq $t3,$zero, loop # if $t3 == 0 it means only spaces detected at this moment
li $t3,0 # else char present before space, set $t3 to 0
addi $s1,$s1,1 # +1 word
j loop
end:
beq $t3,$zero, print_result
li $t3,0
addi $s1,$s1,1
# display number of words
print_result:
move $a0 $s1
li $v0 1
syscall
# exit program
li $v0 10
syscall
.data
A: .space 50 # length of desired string
D: .word -1 # number of words
prompt: .asciiz "Input a string : "
【讨论】: