一.用法
定义:char * strstr( const char *str1, const char *str2 );
•判断str1中是否包含子串str2
•若包含,则返回在str1中子串str2首字符的地址
•若不包含,则返回空指针NULL
例:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[] = "zhangsan";
char arr2[] = "san";
char* ret = strstr(arr1, arr2);
if (ret == NULL)
{
printf("子串不存在\n");
}
else
{
printf("子串存在 且为:%s\n", ret);
}
return 0;
}
运行结果:
二、代码模拟实现
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<assert.h>
//代码模拟实现
char* my_strstr(const char* str1, const char* str2)
{
assert(str1 && str2);
const char* s1 = str1;
const char* s2 = str2;
const char* p = str1;
while (*p)
{
s1 = p;
s2 = str2;
while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2)
{
s1++;
s2++;
}
if (*s2 == '\0')
{
return (char*)p;
}
p++;
}
return NULL;
}
int main()
{
//char email[] = "[email protected]";
//char substr[] = "bitejiuyeke";
//char* ret = my_strstr(email, substr);
char arr1[] = "zhangsan";
char arr2[] = "san";
char* ret = my_strstr(arr1, arr2);
if (ret == NULL)
{
printf("子串不存在\n");
}
else
{
printf("子串存在,且为:%s\n", ret);
}
return 0;
}
运行结果:
以上就是strstr函数的基本用法,欢迎指正~
标签:const,str2,代码,ret,char,strstr,str1,模拟 From: https://blog.51cto.com/u_16210399/7263458