實現 my_strstr:在主串中查找子串,找到返回子串後的剩餘字符串(即標準 strstr 行為),未找到返回 NULL。
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
char *my_strstr(const char *haystack, const char *needle) {
assert(haystack && needle);
if (*needle == '\0') return (char *)haystack;
const char *h = haystack;
while (*h) {
const char *h_start = h;
const char *n = needle;
while (*h && *n && *h == *n) {
h++;
n++;
}
if (*n == '\0') {
return (char *)h_start; // 返回匹配起點
}
h = h_start + 1; // 關鍵:回溯到下一個起始位置
}
return NULL;
}
int main() {
char *s1 = "abcdeff";
char *s2 = "abc";
char *ret = my_strstr(s1, s2);
printf("結果:%s\n", ret ? ret : "NULL");
system("pause");
return 0;
}
結果:abcdeff
s、q 未聲明,邏輯混亂h_start 作為潛在返回值h = h_start + 1,不能直接 h++| 主串 | 子串 | 返回值 | 說明 |
|---|---|---|---|
| "abcdeff" | "abc" | "abcdeff" | 前綴匹配 |
| "abcdeff" | "de" | "deff" | 中間匹配 |
| "abcdeff" | "xyz" | NULL | 不存在 |
| "aaaaa" | "aaa" | "aaaaa" | 返回首個匹配 |