C语言strstr函数源代码
时间: 2023-09-05 22:14:18 浏览: 52
这是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;
}
```
希望可以帮到您。
相关问题
C语言strstr函数详解,源代码
好的,C语言的strstr函数是用于在一个字符串中查找另一个指定的字符串出现的位置的函数。它的源代码是:
char *strstr(const char *haystack, const char *needle);
其中,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。