【问题标题】:how to know how many words are in a string in mips如何知道mips中的字符串中有多少个单词
【发布时间】:2021-03-25 15:34:13
【问题描述】:

我在 A 中有字符串“Hello world”,我想知道有多少个单词组成了 A,我将这个数字保存在 D 中,如下图所示。我该怎么做?

A → “Hello World”

D → 2

【问题讨论】:

  • 您还没有准确定义您认为算作“单词”的内容。也就是说,一个词在哪里开始和结束?一旦你决定了规则,编写一个循环遍历你的字符串并根据你的规则计算一个单词开始的次数。

标签: assembly mips mips32


【解决方案1】:
.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 : "

【讨论】:

  • 这将计算单词 + 1 之间的空格,因此 "Hello World" -> 2 和 "Hello World" -> 3。也许还可以在找到空格后重做修剪。
  • 感谢您的帮助。你测试过这段代码吗?
  • 经过审查是合理的,但是是的,我确实运行它发现 Hello space space World 计数为 3。
猜你喜欢
  • 1970-01-01
  • 2019-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-13
  • 2021-12-04
相关资源
最近更新 更多