String MIPS-检查数组的元素是否为空终止字符
因此,我试图编写一个函数,在MIPS中查找字符串的长度 我在数组中漫游/遍历,加载每个字符,并将每个字符与空终止字符进行比较,以查看字符串是否已“结束”。在每次连续迭代中,我递增一个计数器,然后在字符串“结束”后将计数器存储在$v0中。但是,如何比较当前加载的字符是否为空终止字符“\0”?更具体地说,如何表示这个空终止字符?是零美元吗,就像我在下面做的那样?如果是的话,那么我还做错了什么?获取地址错误String MIPS-检查数组的元素是否为空终止字符,string,mips,String,Mips,因此,我试图编写一个函数,在MIPS中查找字符串的长度 我在数组中漫游/遍历,加载每个字符,并将每个字符与空终止字符进行比较,以查看字符串是否已“结束”。在每次连续迭代中,我递增一个计数器,然后在字符串“结束”后将计数器存储在$v0中。但是,如何比较当前加载的字符是否为空终止字符“\0”?更具体地说,如何表示这个空终止字符?是零美元吗,就像我在下面做的那样?如果是的话,那么我还做错了什么?获取地址错误 .data msg1:.asciiz "Please insert text (max 20
.data
msg1:.asciiz "Please insert text (max 20 characters): "
msg2:.asciiz "\nThe length of the text is: "
newline: .asciiz "\n"
str1: .space 20
.text
.globl main
main:
addi $v0, $v0,4
la $a0,msg1
syscall #print msg1
li $v0,8
la $a0,str1
addi $a1,$zero,20
syscall #get string 1
la $a0,str1 #pass address of str1
jal len
len:
addi $t2, $zero, 0 # $t2 is what we want to return in the end -- the count of the length of the character array
addi $s1, $zero, 0 # Index i for array traversing | init. to 0 | i = 0
Loop:
add $s1, $s1, $a0 # Adds the location of the index to the location of the base of the array | $t1 is now the location of: array[index]
lw $t0, 0($s1)
beq $t0, $zero, exit
addi $t2, $t2, 1 # Count = Count + 1
addi $s1, $s1, 1 # i = i + 1
j Loop
exit:
la $a0,msg2
li $v0,4
syscall
move $a0,$t0 #output the results
li $v0,1
syscall
li $v0,10
syscall
假设您正在处理一个字节字符串,并且正在查找字符串末尾的零字节,则应该使用
lbu$t0,0($s1)
lbu
表示“加载无符号扩展的字节”。然后您可以将$t0
与$zero
寄存器进行比较。当前代码使用lw$t0,0($s1)
将4个字节加载到$t0
中
您的代码中还有一些其他错误,但我将把它们留给您去解决,因为这看起来像是家庭作业。下面的程序计算字符串的长度
.data
theStr: .asciiz "berjee"
.text
main:
li $s1, 0
la $s0, theStr
loop:
lb $a0, 0($s0)
beqz $a0, out
addi $s0, $s0, 1
addi $s1, $s1, 1
j loop
out:
li $v0, 1
add $a0, $0, $s1
syscall
li $v0, 10
syscall
我已经添加了家庭作业标记,如果这不是家庭作业,请随意删除它。为了对此答案提供更多解释,
lb$a0,0($s0)
将寄存器中地址引用的字符串的当前字节偏移量加载到寄存器$s0
和beqz$a0,out
是空终止检查,比较$a0
中的字节与0,如果它们相等,则终止循环。