生成一个C语言的strstr函数 指定最大长度
时间: 2023-12-01 18:02:57 浏览: 44
下面是一个基于暴力匹配算法的 C 语言实现 strstr 函数,其中 max_len 参数指定了最大匹配长度:
```c
#include <stdio.h>
#include <string.h>
char* my_strstr(char* haystack, char* needle, int max_len) {
int n = strlen(haystack);
int m = strlen(needle);
if (m > max_len) {
return NULL;
}
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m && j < max_len; j++) {
if (haystack[i + j] != needle[j]) {
break;
}
}
if (j == m) {
return haystack + i;
}
}
return NULL;
}
int main() {
char haystack[] = "hello, world!";
char needle[] = "world";
char* result = my_strstr(haystack, needle, 10);
if (result) {
printf("Found: %s\n", result);
} else {
printf("Not found\n");
}
return 0;
}
```
注意,该实现并不是最优解,也不适用于所有情况,仅供参考。