2016-03-29 204 views
0

我试图比较两个字符串,因为我添加了整数代码,我posted here before。我可以从用户接收字符串,也可以将其转换为整数,但是在比较字符串时(最大大小为20,如果字符串小于20,将会有空格),我从用户和我的字符“*”中读取时遇到问题。 。我认为,如果我可以比较他们,他们是不相等的,我转换为整数,并继续添加,如果他们是平等的,它将退出循环。比较MIPS中的两个字符串

我写了一个比较两个字符串的简单代码,但是没有给出结果。这是我的代码;

.data 
    str1: .asciiz "Comp" 
    str2: .asciiz "Comp" 
.text 

main: 
    la $s2, str1 
    la $s3, str2 
    move $s6, $s2 
    move $s7, $s3 
    li $s1, 5 


    beq $s6, $s7, exit 

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


exit: 

    li $v0, 10  
    syscall 

当我检查QtSpim的寄存器$ s6和$ s7后,我观察到有不同的值。我怎样才能比较两个字符串?谢谢。

回答

0

该比较涉及指针。那里需要有一个解引用。

lb $s6, ($s2) 
lb $s7, ($s3) 

此外,还需要检查字符串的结尾。

lb $s6, ($s2) 
bz eos 
lb $s7, ($s3) 
bz eos 
+1

当然你不建议通过比较前两个字符是一个比较两个字符串,而是他使用循环比较所有字符一个接一个。他应该看看如何实现'strcmp'。 –

+0

我提供了你的建议,但是我在Qtspim中遇到了语法错误。 – bieaisar

1

我已经调整了您的程序以提示用户输入字符串,因此您可以快速尝试许多值。 cmploop是字符串比较的“肉”,所以如果你愿意,你可以使用它。

下面是它的[请原谅无偿风格清理]:

.data 
prompt:  .asciiz  "Enter string ('.' to end) > " 
dot:  .asciiz  "." 
eqmsg:  .asciiz  "strings are equal\n" 
nemsg:  .asciiz  "strings are not equal\n" 

str1:  .space  80 
str2:  .space  80 

    .text 

    .globl main 
main: 
    # get first string 
    la  $s2,str1 
    move $t2,$s2 
    jal  getstr 

    # get second string 
    la  $s3,str2 
    move $t2,$s3 
    jal  getstr 

# string compare loop (just like strcmp) 
cmploop: 
    lb  $t2,($s2)     # get next char from str1 
    lb  $t3,($s3)     # get next char from str2 
    bne  $t2,$t3,cmpne    # are they different? if yes, fly 

    beq  $t2,$zero,cmpeq    # at EOS? yes, fly (strings equal) 

    addi $s2,$s2,1     # point to next char 
    addi $s3,$s3,1     # point to next char 
    j  cmploop 

# strings are _not_ equal -- send message 
cmpne: 
    la  $a0,nemsg 
    li  $v0,4 
    syscall 
    j  main 

# strings _are_ equal -- send message 
cmpeq: 
    la  $a0,eqmsg 
    li  $v0,4 
    syscall 
    j  main 

# getstr -- prompt and read string from user 
# 
# arguments: 
# t2 -- address of string buffer 
getstr: 
    # prompt the user 
    la  $a0,prompt 
    li  $v0,4 
    syscall 

    # read in the string 
    move $a0,$t2 
    li  $a1,79 
    li  $v0,8 
    syscall 

    # should we stop? 
    la  $a0,dot      # get address of dot string 
    lb  $a0,($a0)     # get the dot value 
    lb  $t2,($t2)     # get first char of user string 
    beq  $t2,$a0,exit    # equal? yes, exit program 

    jr  $ra       # return 

# exit program 
exit: 
    li  $v0,10 
    syscall