您的位置:首页 > 编程语言 > C语言/C++

05:统计单词数 [C语言字符数组的应用]

2017-07-30 10:37 531 查看
05:统计单词数 [C语言字符数组的应用]

总时间限制: 
1000ms 内存限制: 65536kB

描述

一般的文本编辑器都有查找单词的功能,该功能可以快速定位特定单词在文章中的位置,有的还能统计出特定单词在文章中出现的次数。

现在,请你编程实现这一功能,具体要求是:给定一个单词,请你输出它在给定的文章中出现的次数和第一次出现的位置。注意:匹配单词时,不区分大小写,但要求完全匹配,即给定单词必须与文章中的某一独立单词在不区分大小写的情况下完全相同(参见样例1),如果给定单词仅是文章中某一单词的一部分则不算匹配(参见样例2)。

输入2 行。

第 1 行为一个字符串,其中只含字母,表示给定单词;

第 2 行为一个字符串,其中只可能包含字母和空格,表示给定的文章。
输出只有一行,如果在文章中找到给定单词则输出两个整数,两个整数之间用一个空格隔开,分别是单词在文章中出现的次数和第一次出现的位置(即在文章中第一次出现时,单词首字母在文章中的位置,位置从0开始);如果单词在文章中没有出现,则直接输出一个整数-1。
样例输入
样例 #1:
To
to be or not to be is a question

样例 #2:
to
Did the Ottoman Empire lose its power at that time


样例输出
样例 #1:
2 0

样例 #2:
-1


来源
NOIP2011复赛 普及组 第二题

#include <stdio.h>
#include <iostream>
#include <stack>
#include <string.h>
#include <queue>
#include <math.h>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <string>
using namespace std;
typedef long long LL;
#define MAX 100001
int a[MAX];
int b[MAX];

int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
char str1[200], str2[1000005], str3[200] = "";
int first_pos = 0, count = 0;
char *p =NULL;
int i, j , flag;
scanf("%s", str1);
getchar();
gets(str2);

p = str1;
while(*p != '\0'){
if(*p >= 'A' && *p <= 'Z'){
*p = *p + 32;
}
p++;
}
p = str2;
while(*p != '\0'){
if(*p >= 'A' && *p <= 'Z'){
*p = *p + 32;
}
p++;
}
i = 0;
j = 0;
flag = 0;
while(str2[i] != '\0'){
if(str2[i] >= 'a' && str2[i] <= 'z'){
str3[j++] = str2[i];
i++;
}else {
str3[j] = '\0';
if(strcmp(str3, str1) == 0){
count++;
if(!flag){
first_pos=i-strlen(str1);
flag = 1;
}
}
j = 0;
i++;
}
}
if(!flag){
cout << "-1" << endl;
}else {
printf("%d %d", count, first_pos);
}

return 0;

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐