其實,如果你想在一個字符逐個字符的基礎兩個字符串合併,正確的輸出是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
,我想要的是「LALAL」,但輸出感謝小費 –
的'jloahn'基於你的問題標題[_「從字符串」john「和」la「串聯兩個字母串」_「]。一個簡單的字concat將是'johnla'。所以,我不確定你是如何從_two_字符串到只重複第二個字符串(即lalal)的東西,長度分別是5和4,輸入長度分別是4和2。所以,編輯你的問題可能會對你有所幫助,以澄清這個問題,因爲對於我來說,至少用什麼算法來組合兩個輸入字符串並生成lalal輸出並不是顯而易見的。 –