如何在MIPS上实现strstr函数
时间: 2024-05-12 22:17:37 浏览: 16
在 MIPS 上实现 strstr 函数需要使用指针来定位目标字符串和子字符串的位置,具体实现可以参考以下代码:
```
#include <stdio.h>
char *my_strstr(char *str1, char *str2) {
int len1, len2;
char *p1, *p2;
len1 = strlen(str1);
len2 = strlen(str2);
if (len1 < len2) return NULL;
for (p1 = str1; *p1; p1++) {
p2 = str2;
while (*p2 && (*p1 == *p2)) {
p1++;
p2++;
}
if (!*p2) return (p1 - len2);
p1 = p1 - (p2 - str2);
}
return NULL;
}
int main(void) {
char str1[] = "hello world";
char str2[] = "world";
printf("Result: %s\n", my_strstr(str1, str2));
return 0;
}
```
其功能是在 str1 中查找 str2,如果找到则返回 str2 在 str1 中的起始位置,否则返回 NULL。
相关问题
MIPS调用c语言的strstr函数举例
可以使用以下代码实现:
char *str = "Hello World!";
char *substr = "World";
char *result = strstr(str, substr);
if (result != NULL) {
printf("Substring found at index: %d", result - str);
} else {
printf("Substring not found");
}
这是一个简单的示例,用于在字符串中查找一个子字符串。
strstr函数翻译成mips
MIPS指令集下的strstr函数翻译可以采用以下代码:
```
## $a0 - string1, $a1 - string2, $t0 - temp, $t1 - temp
str_instr:
li $v0, 0 # 子串出现次数
la $t0, ($a0) # 获取字符串1首地址
la $t1, ($a1) # 获取字符串2首地址
lw $t2, 0($t1) # 获取字符串2首字符
loop:
beqz $t2, end # 字符串2扫描结束则退出
li $t3, 0 # 计数器清零
lw $t4, 0($t0) # 初始化字符串1首字符
match:
beqz $t4, not_match # 字符串1扫描结束则退出
bne $t2, $t4, next # 字符不匹配则跳转
addi $t0, $t0, 4 # 匹配则扫描下一个字符
addi $t1, $t1, 4
lw $t4, 0($t0)
lw $t2, 0($t1) # 加载字符串2下一个字符
addi $t3, $t3, 1 # 匹配次数递增
bne $t3, $t8, match # 继续匹配下一个字符
match_end:
addi $t0, $t0, -($t3 * 4) # 复位字符串1指针
addi $v0, $v0, 1 # 统计匹配次数
j next
not_match:
addi $t0, $t0, 4 # 字符串1指针回溯
b next
next:
lw $t4, 0($t0) # 加载字符串1下一个字符
b loop
end:
jr $ra
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)