2016-03-29 199 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