MIPS找到字符串的结尾

时间:2018-06-01 12:38:02

标签: mips32

我有以下mips代码(在QTSPIM中运行),它应该计算字符串中的字符数并打印它们。

它背后的逻辑非常简单,但不能正常工作。一切顺利,直到它到达字符串的末尾然后它继续计数,即使我将每个元素比较为$ 0以找到字符串的结尾(\ 0)。

我的条件退出循环是否有问题,或者 my_string 最终不包含\ 0因此它不会退出?

    .data
endl: .asciiz "\n"
my_string: .asciiz "thisisastring"
star: .asciiz "*"
str_end: .word 0
space: .asciiz " "

    .text
    .globl main

main:
    la $a0, my_string
    li $v0, 4
    syscall

    la $a0, endl
    li $v0, 4
    syscall

    la $t0, my_string   #   load mystring to $t0
    li $t1, 0           #   make $t1 = 0, character counter
    lb $t2, ($t0)       #   make $t2 point to the first character of "my_string"
    li $t3, 1           #   $t3 is the ++ register to go to the next character  
    li $t4, 0           #   character counter
    la $t5, str_end

cont:
    beqz $t0, print #   if \0 is found print and exit
    addi $t4, $t4, 1        #   increase the counter

    lbu $a0, ($t0)          #   print current character
    li $v0, 11
    syscall

    addi $t0, $t0, 1        #   go to next char
    #move $t2, $t0


    j cont

print:
    move $a0, $t4
    li $v0, 1
    syscall
    j exit

exit:
    li $v0, 10
    syscall

1 个答案:

答案 0 :(得分:1)

问题在于指令的顺序,即代码的逻辑。

以下是没有冗余代码的更正版本:

    .data
endl: .asciiz "\n"
my_string: .asciiz "thisisastring"
str_end: .word 0

    .text
    .globl main

main:
    la $a0, my_string
    li $v0, 4           #   print the string
    syscall

    la $a0, endl        #   print endl
    li $v0, 4
    syscall

    la $t0, my_string   #   load mystring to $t0
    li $t1, 0           #   make $t1 = 0, character counter
    lb $t2, 0($t0)      #   make $t2 point to the first character of "my_string"
    la $t5, str_end

cont:
    lb $a0, 0($t0)          #   print current character
    beqz $a0, print         #   if \0 is found print and exit

    addi $t1, $t1, 1        #   increase the counter
    addi $t0, $t0, 1        #   go to next char

    li $v0, 11
    syscall

    j cont


print:
    move $a0, $t1
    li $v0, 1
    syscall
    j exit

exit:
    li $v0, 10
    syscall