比较MIPS中的字符串

时间:2015-11-25 03:43:24

标签: assembly mips mips32

以下代码比较两个字符串。如果在Input中找到C,它会递增计数器。我想知道我的代码中的问题在哪里。它没有给出输出。

.data
Input: .asciiz "\nThis is Lab-05 of the course CSCS323 Computer Organization and Assembly Language.We are FCCU/CS Students"
Check: .asciiz "C"
Result: .asciiz "\nThe number of times this character occurs in the string is: "
.text
.globl main
 main:

 la $t0, Input #load address of input
 la $t1, Check #load address of Check
 li $s1, 0     #Set Counter to zero

compare:
lb $t2, 0($t0)
lb $t3, 0($t1)

beq $t2, $t3, counter
addi $t0, $t0, 1

counter:
addi $s1, $s1, 1
jr $ra

add $a0 , $s1 , $zero
li $v0, 1
move $a0, $s1
syscall

1 个答案:

答案 0 :(得分:1)

jr指令错误。你从那里的子程序返回。你想要j compare

lb $t3,0($t1)在整个循环中不变(例如,您递增$t0但不递增$t1),因此您可以在compare:之前移动指令

Input扫描结束时,您不会退出比较循环。也就是说,在lb $t2,0($t0)之后。您需要将$ t2与零进行比较

如果您分支到$t0,则不会增加counter:。这意味着你将无限循环[固定jr]。

您没有使用Result字符串

这是更正后的代码。它可能不完美,但它更接近[请原谅无偿的风格清理]:

.data
Input: .asciiz "\nThis is Lab-05 of the course CSCS323 Computer Organization and Assembly Language.We are FCCU/CS Students"
Check: .asciiz "C"
Result: .asciiz "\nThe number of times this character occurs in the string is: "

.text
.globl main
main:
    # output the result string
    li      $v0,4               # print_string syscall number
    la      $a0,Result          # string address
    syscall

    la      $t0,Input           # load address of Input
    li      $s1,0               # Set Counter to zero

    la      $t1,Check           # load address of Check
    lb      $t3,0($t1)          # get "check" char value

    li      $s2,0               # get end of string (EOS) char

compare:
    lb      $t2,0($t0)          # get next char in 'Input'
    addi    $t0,$t0,1           # advance pointer to next char

    beq     $t2,$s2,done        # is current char 0?  if yes, fly and print

    bne     $t2,$t3,compare     # does current match check? If no, loop
    addi    $s1,$s1,1           # yes, increment count
    b       compare             # loop

done:
    li      $v0,1               # print_int syscall
    move    $a0,$s1             # get total count to correct register
    syscall