你好我一直试图连接字符串输入是两个字符串:" john"和" la"它应该打印" lala"相反,它打印" llll"我无法解决它。
.data
texto: .asciiz "john"
cifra: .asciiz "la"
.text
la $a0,texto #pass address of str1
la $a1,cifra #pass address of str2
jal conc
conc:
add $t1,$zero,$a0
add $t2,$zero,$a1
loop:
lb $t3($t1)
lb $t4($t2)
lbu $t4,0($a1)
sb $t4, 0($a1)
beq $t3, $zero, end
nop
move $a0,$t4
li $v0, 11
syscall
addi $t1, $t1, 1
addi $t2,$t2, 1
j loop
end:
答案 0 :(得分:0)
实际上,如果你想在逐个字符的基础上合并两个字符串,那么正确的输出是jloahn
您的代码甚至无法汇编。而且,它只会使用两个字符串中的一个。我提供了两个版本。一个是用错误注释的。另一个是完全修正的版本[请原谅无偿的风格清理]。
带注释的版本:
.data
texto: .asciiz "john"
cifra: .asciiz "la"
.text
la $a0,texto # pass address of str1
la $a1,cifra # pass address of str2
jal conc
# BUG: no exit program
li $v0,10
syscall
conc:
add $t1,$zero,$a0
add $t2,$zero,$a1
loop:
# BUG: these won't even assemble
###lb $t3($t1)
###lb $t4($t2)
lb $t3,0($t1)
lb $t4,0($t2)
# BUG: these fetch from $a1 which is never incremented -- in other words,
# t4 will always get the same first char (i.e. "l")
###lbu $t4,0($a1)
###sb $t4,0($a1)
beq $t3,$zero,end
nop
# output next char
# BUG: this only outputs chars from one string
move $a0,$t4
li $v0,11
syscall
addi $t1,$t1,1
addi $t2,$t2,1
j loop
end:
jr $ra
已清理并更正的版本:
.data
texto: .asciiz "john"
cifra: .asciiz "la"
out: .space 80
.text
la $a0,out # get address of output
la $a1,texto # pass address of str1
la $a2,cifra # pass address of str2
jal conc
# output the concatenated string
la $a0,out
li $v0,4
syscall
# BUG: no exit program
li $v0,10
syscall
# conc -- concatenate strings char-by-char
#
# arguments:
# a0 -- output pointer
# a1 -- pointer to string to concatenate
# a2 -- pointer to string to concatenate
conc:
lb $t1,0($a1) # get string char
beqz $t1,conc_no1st # EOS? if yes, skip
addi $a1,$a1,1 # advance 1st source pointer
sb $t1,0($a0) # add to output
addi $a0,$a0,1 # advance output pointer
conc_no1st:
lb $t2,0($a2) # add to output
beqz $t2,conc_no2nd # EOS? if yes, skip
addi $a2,$a2,1 # advance 2nd source pointer
sb $t2,0($a0) # add to output
addi $a0,$a0,1 # advance output pointer
conc_no2nd:
or $t1,$t1,$t2 # both chars EOS?
bnez $t1,conc # no, loop
sb $zero,0($a0) # store final EOS
jr $ra