自己编写strstr函数,不使用指针
时间: 2024-05-12 12:19:38 浏览: 10
以下是一个不使用指针的strstr函数的实现:
```c
char* my_strstr(char* haystack, char* needle) {
// 获取字符串长度
int haystack_len = 0;
while (haystack[haystack_len] != '\0') {
haystack_len++;
}
int needle_len = 0;
while (needle[needle_len] != '\0') {
needle_len++;
}
// 在haystack中查找needle
for (int i = 0; i <= haystack_len - needle_len; i++) {
bool match = true;
for (int j = 0; j < needle_len; j++) {
if (haystack[i+j] != needle[j]) {
match = false;
break;
}
}
if (match) {
return &haystack[i];
}
}
// 没有找到
return NULL;
}
```
该函数首先获取haystack和needle的长度,然后在haystack中遍历每个可能的开始位置,比较haystack中以该位置开始的needle长度的子串是否与needle相同。如果找到了匹配的子串,则返回该子串在haystack中的起始位置,否则返回NULL。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)