string - MIPS - 检查数组的元素是否为空终止字符

标签 string mips

所以我正在尝试编写一个函数来查找 MIPS 中字符串的长度。

我正在沿着数组走/遍历,加载每个字符,我想将每个字符与空终止字符进行比较,看看字符串是否已“结束”。在每次连续迭代中,我递增一个计数器,然后在字符串“结束”后将计数器存储在 $v0 中。但是,如何比较当前加载的字符是否为空终止符“\0”?更具体地说,我如何表示这个空终止字符?它是零美元吗,就像我在下面所做的那样?如果是这样,那我还做错了什么?获取地址错误。

.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

您的代码中还有其他一些错误,但我会把它们留给您去解决,因为这看起来像是家庭作业。

关于string - MIPS - 检查数组的元素是否为空终止字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12379397/

相关文章:

python - 正则表达式拆分包装模式

linux - 在 MIPS TLB 中,除了 ASID 字段之外,两个条目是否可能相同?

将 C 交叉编译为 MIPS64 并进行仿真

c - 在 ubuntu 中为 MIPS 编译 netcat 的问题

sql - 从字符串 SQL Netezza 中提取序列号

java - 如何找到 String.indexOf ("\")?

javascript - 有效地替换字符串中的所有重音字符?

Python "while"循环没有结束

C语言转MIPS。斐波那契数

mips - 如何从 MIPS 中的主函数返回一个值?