曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 6253|回复: 0
打印 上一主题 下一主题

[字符串] strstr() -- 检查字符串包含

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2009-5-4 11:17:35 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
函数原型
#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
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-6 08:30 , Processed in 0.064436 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表