您的位置:首页 > 其它

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

2014-03-13 00:10 295 查看
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++ 容器笔记;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  指针