当自己在学习这个函数的时候很纠结,现在将自己总结的整理如下:
包含文件:string.h
函数名: strstr
函数原型:
extern char *strstr(char *str1, const char *str2);
语法:
strstr(str1,str2)
str1: 被查找目标 string expression to search.
str2: 要查找对象 The string expression to find.
返回值:若str2是str1的子串,则返回str2在str1的首次出现的地址;如果str2不是str1的子串,则返回NULL。
int main(void)
{
char *str1 = "Borland International", *str2 = "nation", *ptr;
ptr = strstr(str1, str2);
printf("The substring is: %s\n", ptr);<span style="white-space:pre"> </span>//结果是<span style="font-family: arial, 宋体, sans-serif;">national</span>
return 0;
}
结果为:The substring is: national
我们在举个例子:用于计算含有多少个子串
//用于计算含有多少个子串
void main()
{
char * p = "abcd1111abcd2222abcd333abcd";
//保存子串的个数
int count = 0;
do
{
//进行查找
p = strstr(p, "abcd");
if (p==NULL) //不存在则终止
{
break;
}
else
{
//将当前的p的指针位置进行打印输出
printf("当前的指针位置 = %s\n", p);
//子串个数自增
count++;
//将p的指针向前移动
p = p + strlen("abcd");
}
} while (*p != '\0');
printf("count = %d \n", count);
system("pause");
}
结果: