strstr函数源代码不用strncmp函数
时间: 2023-10-18 09:21:21 浏览: 38
以下是一个简单的 strstr 函数的源代码,不使用 strncmp 函数:
```c
char *my_strstr(const char *haystack, const char *needle) {
if (!*needle) {
return (char*)haystack;
}
const char *p1 = haystack;
while (*p1) {
const char *p1_start = p1, *p2 = needle;
while (*p1 && *p2 && *p1 == *p2) {
p1++;
p2++;
}
if (!*p2) {
return (char*)p1_start;
}
p1 = p1_start + 1;
}
return NULL;
}
```
该函数首先检查 needle 是否为空字符串,如果是,则返回 haystack 指针。然后在一个 while 循环中遍历 haystack 字符串,对于 haystack 中的每个字符,它会尝试将 needle 与 haystack 中的子字符串进行比较。如果找到了 needle,则返回 haystack 的开始位置。如果没有找到,则继续搜索。如果 haystack 中没有 needle,则返回 NULL。
相关问题
strstr函数源代码
以下是C语言的strstr函数源代码:
```
#include <stdio.h>
#include <string.h>
char *strstr(const char *haystack, const char *needle) {
size_t needle_len;
if (*needle == '\0')
return (char *) haystack;
needle_len = strlen(needle);
while (*haystack != '\0') {
if (*haystack == *needle) {
if (strncmp(haystack, needle, needle_len) == 0)
return (char *) haystack;
}
haystack++;
}
return NULL;
}
```
该函数的作用是在一个字符串中查找另一个字符串,如果找到则返回第一个字符串中第一个匹配到的子串的地址。如果没有找到,则返回NULL。
C语言strstr函数源代码
这是C语言中strstr函数的源代码:
```C
char *strstr(const char *haystack, const char *needle) {
char *p1 = (char *) haystack, *p2 = (char *) needle;
char *p1Adv = (char *) haystack;
if (*needle == '\0') {
return (char *) haystack;
}
for (; *p1Adv; p1 = p1Adv++) {
p2 = (char *) needle;
if (*p1 != *p2) {
continue;
}
while (*++p1 && *++p2) {
if (*p1 != *p2) {
break;
}
}
if (*p2 == '\0') {
return p1;
}
}
return NULL;
}
```
希望可以帮到您。