How to concatenate string in MIPS?

19,968

Quick and dirty:

# String concatenate

.text

# Copy first string to result buffer
la $a0, str1
la $a1, result
jal strcopier
nop

# Concatenate second string on result buffer
la $a0, str2
or $a1, $v0, $zero
jal strcopier
nop
j finish
nop

# String copier function
strcopier:
or $t0, $a0, $zero # Source
or $t1, $a1, $zero # Destination

loop:
lb $t2, 0($t0)
beq $t2, $zero, end
addiu $t0, $t0, 1
sb $t2, 0($t1)
addiu $t1, $t1, 1
b loop
nop

end:
or $v0, $t1, $zero # Return last position on result buffer
jr $ra
nop

finish:
j finish
nop

.data
str1:
.asciiz "Hello "
str2:
.asciiz "world"
result:
.space 200

If you don't understand something, don't hesitate to ask.

Have fun :)

Share:
19,968
Jiew Meng
Author by

Jiew Meng

Web Developer & Computer Science Student Tools of Trade: PHP, Symfony MVC, Doctrine ORM, HTML, CSS, jQuery/JS Looking at Python/Google App Engine, C#/WPF/Entity Framework I hope to develop usable web applications like Wunderlist, SpringPad in the future

Updated on July 14, 2022

Comments

  • Jiew Meng
    Jiew Meng almost 2 years

    How do I concatenate a string in MIPS? I think I will somehow have to know the length of the string?