我试图比较两个字符串,因为我添加了整数代码{{3}}。我可以从用户获取字符串,也将其转换为整数,但我在比较字符串时遇到问题(最大大小为20,如果字符串小于20,则会有空格)从用户和我的角色中读取#34 ; *"。我认为如果我可以比较它们并且它们不相等,我转换为整数并继续添加,如果它们相等则它将从循环中退出。
我写了一个简单的代码来比较两个字符串,但是没有给出结果。这是我的代码;
.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 :(得分:2)
我已经调整了你的程序以提示用户输入字符串,因此你可以快速尝试很多值。 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
答案 1 :(得分:0)
比较涉及指针。需要在那里进行解除引用。
lb $s6, ($s2)
lb $s7, ($s3)
此外,还需要检查字符串的结尾。
lb $s6, ($s2)
bz eos
lb $s7, ($s3)
bz eos
答案 2 :(得分:0)
使用MIPS编译的简单String Compare,打印遇到的第一个不匹配字符的ASCII差异
.text
.globl main
main:
li $v0, 4
la $a0, msg1
syscall
li $v0, 8
la $a0, string1
li $a1, 99
syscall
li $v0, 4
la $a0, msg2
syscall
li $v0, 8
la $a0, string2
li $a1, 99
syscall
lb $t5, endline
# compare each bit
la $t1, string1
la $t2, string2
loop:
# load the characters
lb $t3, 0($t1)
lb $t4, 0($t2)
# check if equal, if not stop loop, if equal, then continue
sub $t6, $t3, $t4
beq $t6, $zero, continueEqual
j end_loop
continueEqual:
# if t3 or t4 == '\n' stop loop
beq $t3, $t5, end_loop
# continue again, by incrementing both address by one
addi $t1, $t1, 1
addi $t2, $t2, 1
j loop
end_loop:
beq $t6, $zero, same
notSame:
li $v0, 4
la $a0, msg4
syscall
j printRes
same:
li $v0, 4
la $a0, msg3
syscall
printRes:
li $v0, 1
move $a0, $t6
syscall
li $v0, 4
la $a0, endline
syscall
exit:
li $v0, 10
syscall
.data
msg1: .asciiz "Enter string-1: "
msg2: .asciiz "Enter string-2: "
msg3: .asciiz "Same\n"
msg4: .asciiz "Not Same\n"
endline: .asciiz "\n"
string1: .space 100
string2: .space 100