题目链接:P1308
题目描述
一般的文本编辑器都有查找单词的功能,该功能可以快速定位特定单词在文章中的位置,有的还能统计出特定单词在文章中出现的次数。
现在,请你编程实现这一功能,具体要求是:给定一个单词,请你输出它在给定的文章中出现的次数和第一次出现的位置。注意:匹配单词时,不区分大小写,但要求完全匹配,即给定单词必须与文章中的某一独立单词在不区分大小写的情况下完全相同,如果给定单词仅是文章中某一单词的一部分则不算匹配。
代码实现
#include <bits/stdc++.h>
using namespace std;
int main ()
{
string ch,src;
int cnt=0,pos=0,k=0;
getline(cin,src);
getline(cin,ch);
for(int i=0;i<ch.length();i++) {
if(ch[i]>='A'&&ch[i]<='Z') ch[i]+=32;
}
for(int i=0;i<src.length();i++) {
if(src[i]>='A'&&src[i]<='Z') src[i]+=32;
}
ch=" "+ch+" ";
src=" "+src+" ";
while(ch.find(src,pos)!=string::npos) { //found the word in scope
pos=ch.find(src,pos);
cnt++;
if(cnt==1) k=pos;
pos++;
}
if(cnt==0) cout<<-1;
else cout<<cnt<<" "<<k;
return 0;
}