C 字符串查找 - strstr()
描述
C 库函数 char *strstr(const char *haystack, const char *needle) 在字符串 haystack 中查找第一次出现字符串 needle 的位置,不包含终止符 '\0'。
声明
下面是 strstr() 函数的声明。
c
char *strstr(const char *haystack, const char *needle)
参数
- haystack -- 要被检索的 C 字符串。
- needle -- 在 haystack 字符串内要搜索的小字符串。
- haystack 干草堆
- needle 针
来源推导: 干草堆里捞针/大海
返回值
该函数返回在 haystack 中第一次出现 needle 字符串的位置,如果未找到则返回 null。
cpp
#include <stdio.h>
char *my_strstr(const char *str1, const char *str2) {
// 防御性检查(增强健壮性)
if (str1 == NULL || str2 == NULL) return NULL;
// 如果 str2 是空串,返回 str1
if (!*str2) return (char *)str1;
char *cp = (char *)str1; // 临时指针,遍历起点
char *s1, *s2;
while (*cp) {
s1 = cp;
s2 = (char *)str2;
// 逐字符比较(这里的写法改成了直观的 ==)
while (*s1 && *s2 && (*s1 == *s2)) {
s1++;
s2++;
}
// 如果 s2 走到了末尾,说明完全匹配
if (!*s2) return cp;
cp++; // 起点后移一位,继续尝试
}
return NULL; // 没找到
}
int main() {
char *p1 = "abcddefdef";
char *p2 = "def";
char *ret = my_strstr(p1, p2);
if (ret == NULL)
printf("子串不存在\n");
else
printf("%s\n", ret); // 输出 "defdef"
return 0;
}