首页 > 其他 > 详细

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

时间:2014-03-13 10:05:03      阅读:555      评论:0      收藏:0      [点我收藏+]
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++ 容器笔记;

ACM/ICPC 常用函数---strstr()字符串查找函数,布布扣,bubuko.com

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

原文:http://blog.csdn.net/keshacookie/article/details/21129483

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!