|
函数原型:
#include <string>
char *strstr(const char *haystack, const char *needle); 描述:
haystack 和 needle 各指向一个字符串。此函数在 haystack 中查找是否有匹配 needle 的字符串,有的话就返回一个指向从匹配点开始到 haystack 字符串末尾的指针,找不到则返回空指针。
测试代码:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[50] = "我爱我的祖国";
char str2[50] = "我的";
printf("第一个字符串:%s\n", str1);
printf("第二个字符串:%s\n",str2);
printf("找到:%s\n",strstr(str1, str2));
return 0;
} 运行输出:beyes@linux-beyes:~/C/base> ./strstr.exe
第一个字符串:我爱我的祖国
第二个字符串:我的
找到:我的祖国
注意,如果上面中第二个字符串中的元素都为 ‘\0' (NULL),那么函数不会去比较这个 NULL,直接结束函数,此时完整输出第一个字符串中的内容,即返回第一个字符串的指针:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[50] = "我爱我的祖国";
char str2[3] = "\0\0\0";
printf("第一个字符串:%s\n", str1);
printf("第二个字符串:%s\n",str2);
printf("找到:%s\n",strstr(str1, str2));
if(!strstr(str1, str2)) {
printf("not match\n");
}
return 0;
} 运行输出:beyes@linux-beyes:~/C/base> ./strstr.exe
第一个字符串:我爱我的祖国
第二个字符串:
找到:我爱我的祖国
如果第二个字符串指针所指向的第一个元素不是NULL,而是其他普通的字符,那么比较不匹配时就会输出NULL:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[50] = "我爱我的祖国";
char str2[50] = "我的母亲";
printf("第一个字符串:%s\n", str1);
printf("第二个字符串:%s\n",str2);
printf("找到:%s\n",strstr(str1, str2));
if(!strstr(str1, str2)) {
printf("not match\n");
}
return 0;
} 运行输出:beyes@linux-beyes:~/C/base> ./strstr.exe
第一个字符串:我爱我的祖国
第二个字符串:我的母亲
找到:(null)
not match |
|