题目描述
一般的文本编辑器都有查找单词的功能,该功能可以快速定位特定单词在文章中的位置,有的还能统计出特定单词在文章中出现的次数。
现在,请你编程实现这一功能,具体要求是:给定一个单词,请你输出它在给定的文章中出现的次数和第一次出现的位置。注意:匹配单词时,不区分大小写,但要求完全匹配,即给定单词必须与文章中的某一独立单词在不区分大小写的情况下完全相同(参见样例1 ),如果给定单词仅是文章中某一单词的一部分则不算匹配(参见样例2 )。
输入格式
共2行。
第1行为一个字符串,其中只含字母,表示给定单词;
第2行为一个字符串,其中只可能包含字母和空格,表示给定的文章。
输出格式
一行,如果在文章中找到给定单词则输出两个整数,两个整数之间用一个空格隔开,分别是单词在文章中出现的次数和第一次出现的位置(即在文章中第一次出现时,单词首字母在文章中的位置,位置从0 开始);如果单词在文章中没有出现,则直接输出一个整数−1。
输入输出样例
输入 #1
To
to be or not to be is a question
输出 #1
2 0
输入 #2
to
Did the Ottoman Empire lose its power at that time
输出 #2
-1
说明/提示
数据范围
1≤单词长度≤10。
1≤文章长度≤1,000,000。
noip 2011普及组第2题
题目大意及分析
本题就需要你去查找一个字符串,判断它出现次数和第一次出现的位置。思路很清晰,但要注意细节的处理,不然也不太容易全部AC。
代码
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int x=0,y=-1,z=0;
string s,str;
cin >> s;
getchar();
transform(s.begin(), s.end(), s.begin(), ::toupper);//将需要查找的单词字母全部换成大写;
getline(cin,str);
transform(str.begin(), str.end(), str.begin(), ::toupper);//将文章每一字母也都转为大写;
for(int i=0;str[i]!='\0';i++)
{
int j=i;
string ans;
while(str[j]!=' '&&str[j]!='\0')//将单个单词提取出来(没有空格);
{
ans+=str[j];
j++;
}
if(i!=j)
{
if(s.compare(ans)==0)//和所需要查找的单词进行对比;
{
x++;
if(y<0) y=z;
}
else
{
z+=ans.size()-1;//记录每一个单词首字母在所有字符中的顺序;
}
i=j-1;
}
z++;
}
if(x==0)
{
cout << "-1" << endl;
return 0;
}
cout << x << " " << y <<endl;
return 0;
}
知识点补充
在进行string类型中大小写字母转换的时候,用到了STL模板函数toupper/tolower;一个简单的例子如下,相信很容易看懂。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str = "abcdEFGHIJK";
transform(str.begin(), str.end(), str.begin(), ::toupper);//全部变成大写
cout << str << endl;
transform(str.begin(), str.end(), str.begin(), ::tolower);//全部变成小写
cout << str << endl;
return 0;
}