2024年3月26日发(作者:)
strstr函数代码
strstr函数是一个C语言中的字符串函数,其作用是在一个字
符串中查找另一个字符串的位置并返回。以下是strstr函数的代码
实现:
```
#include
#include
char *strstr(char *str1, char *str2)
{
char *p = str1;
char *q = str2;
char *s = NULL;
while (*p)
{
s = p;
while (*s && *q && (*s == *q))
{
s++;
q++;
}
if (!*q)
{
- 1 -
return p;
}
q = str2;
p++;
}
return NULL;
}
int main()
{
char str1[100] = 'hello, world!';
char str2[10] = 'world';
char *p;
p = strstr(str1, str2);
if (p)
{
printf('%s is found in %s
', str2, str1);
}
else
{
printf('%s is not found in %s
', str2, str1);
- 2 -
}
return 0;
}
```
该函数的实现过程是:首先利用两个指针p、q来指向要查找的
两个字符串的首字符,然后用一个指针s来遍历str1字符串。在遍
历s时,如果s和q指向的字符相等,则继续遍历,否则p指针向后
移动一位,q指针重新指向str2的首位。在遍历过程中,如果q指
针指向字符串的末尾,则返回p指针的位置,即表示找到了str2在
str1中的位置。如果遍历完整个str1字符串,还未找到str2,则返
回NULL。
在main函数中,先定义两个字符串str1和str2,并用strstr
函数查找str2在str1中的位置。如果返回的指针不为空,则表示找
到了str2,否则表示没有找到。最后根据返回的指针输出相应的结
果。
以上就是strstr函数的代码实现及其基本用法。
- 3 -


发布评论