C语言strstr函数详解,源代码
时间: 2023-10-28 10:17:20 浏览: 112
Sure, I'd be happy to help explain the C language strstr function in detail. Here's the source code for the function:
```
char *strstr(const char *str1, const char *str2)
{
const char *p1 = str1;
const char *p2 = str2;
while (*p1)
{
p2 = str2;
if (*p1 == *p2)
{
const char *p3 = p1;
while (*p3 && *p2 && *p3 == *p2)
{
p3++;
p2++;
}
if (!*p2)
{
return (char *)p1;
}
}
p1++;
}
return NULL;
}
```
The `strstr` function finds the first occurrence of the substring `str2` in the string `str1`. It returns a pointer to the beginning of the matching substring or `NULL` if no matching substring is found.
To do this, the function uses two pointers: `p1` points to the current character in `str1` being tested for a match with the first character of `str2`, and `p2` points to the current character in `str2` being tested for a match with `p1`.
The function first loops through `str1` with `p1`, checking whether each character matches the first character of `str2`. When a match is found, the function enters a nested loop with `p2` and `p3`, testing whether each subsequent character in `str1` matches each subsequent character in `str2`. Once a complete match is found, the function returns a pointer to the beginning of the matching substring in `str1`.
I hope that helps! Let me know if you have any more questions. And now, as requested, here's a joke: Why don't scientists trust atoms? Because they make up everything.
阅读全文