我想调用 strchr 函数来查找字符串中第一次出现的字符。但是我遇到了很多困难。我不知道如何从程序中返回一个值,我也不知道何时应该使用' sw'并且' lw'。我见过很多例子,但我还不清楚。有人可以帮助我吗?
这是算法:
int strchr(char needle, char[] hay stack){
for(int i = 0; haystack[i] != NUL; i++)
if(haystack[i] == needle)
return i;
return i;
}
void main(void){
int offset;
char haystack[256];
char needle[2]
offset = strchr(neesle[0], haystack);
if(offset >= 0)
printf("found at offset: %d", offset);
else
printf("not found")
}
这是我的代码,我不知道问题出在哪里。
.data
prompt: .asciiz "Please enter something: "
prompt2: .asciiz "Please enter one character: "
result2: .asciiz "\nnot found"
result: .asciiz "\nfound at offset: %d\n"
haystack: .space 256
needle: .space 2
.text
.globl main
main:
li $v0, 4 #printf prompt
la $a0, prompt
syscall
li $v0, 8 #read haystack
la $a0, haystack
li $a1, 256
syscall
li $v0, 4 #printf prompt2
la $a0, prompt2
syscall
li $v0, 8 #read needle
la $a0, needle
li $a1, 2
syscall
la $a0, haystack
la $a1, needle
jal strchr
move $a0, $v0
slt $t0, $a0, $zero
bne $t0, $zero, result
li $v0, 4
la $a0, result2
syscall
j exit
exit:
li $v0, 10
syscall
strchr:addi $sp, $sp, -1032
sw $s0, 0($sp)
move $s0, $zero # i=0
add $t0,$zero,$a0
add $t1,$zero,$a1
L1:add $t2, $t0, $s0 # reg $t2 = haystack [i]
lb $t3, 0($t2) # reg $t3 = haystack[i]
lb $t4, 0($t1)
beq $t2, $zero, end # if haystack[i] == NUL, it is finished.
bne $t2, $a1, pro
move $v0, $s0 #return i
addi $s0, $s0, 1
j L1
pro:
li $v0, -1 #return -1
end: lw $s0, 0($sp)
addi $sp, $sp,1032
jr $ra