ACM/ICPC 常用函数---strstr()字符串查找函数

char *strstr(char *str1, char *str2)

该函数的作用是在字符串str1中寻找str2字符串的位置,并返回指向该位置的指针,如果没有找到相匹配的就返回空指针;


Here is a sample program for the use of the function:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#define MAXN 256
using namespace std;

int main()
{
    char str1[MAXN], str2[MAXN];
    while(~scanf("%s %s", str1, str2)) {
        char *pos = strstr(str1, str2);   //注意:该函数返回的是一个char 类型的指针,而不是int型的;
        if(pos != NULL) puts("YES");
        else puts("NO");
    }
    return 0;

}


HLG 1620 小Z的卡片----

链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1620


#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#define MAXN 105
using namespace std;

typedef struct Node_  //Node后面的下划线只是个人编程的习惯;非语法需要;
{
    char s[MAXN];
}Node;

Node N[15];
char str[MAXN];

int main()
{
    int cas, n;
    scanf("%d", &cas);
    getchar();       //吸收换行符;

    while(cas--) {
        scanf("%d", &n);
        for(int i=0; i<n; i++) {
            scanf("%s", N[i].s);
        }
        scanf("%s", str);
        int count = 0;
        for(int i=0; i<n; i++) {
            char *pos = strstr(str, N[i].s);  //定义字符型的位置指针;该指针指向s2在s1中出现的位置;
            if(pos != NULL) count++;   //如果pos不为空,则表示找到了;否则没找到;
        }
        printf("%d\n", count);
    }
    return 0;
}


当然这道题还可以用到C++ set容器, 用set <string> s; s,find(s2);查找函数即可; C++set容器的具体用法请看我的博客C++ 容器笔记;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值