- 使用前提条件:string.h头文件
- 功能:判断一个字符串是否为另一个字符串的子串
- 函数的使用方法:
int if_sub = strstr(str1,str2);
其中第一个字符串str1可看作母串,第二个则为可能的子串。
如果str2是str1的子串,则返回str2第一次在str1中出现的地址;
如果不是,则返回空指针(NULL)
具体实现效果如下
#include "stdio.h"
#include "string.h"
int main(void)
{
char* str1 = "HelloWorld";
char* str2 = "World";
char* if_sub = strstr(str1,str2);
if (NULL == if_sub)\\小声bb:在判断一个指针是否为空指针时,最好使用该形式而不是smt == NULL否则可能会造成错误
{
printf("The str2 is NOT the substring of the str1\n");
}
else printf("The str2 is the substring of the str1");
return 0;
}
运行解果:
The str2 is the substring of the str1
进程已结束,退出代码为 0
- 请注意,
strstr
函数是区分大小写,因此 "World" 和 "world" 会被认为是不同的字符串。如果需要执行不区分大小写的搜索,会有类似的函数(如strcasestr)来执行类似的功能。