题解:P1308 [NOIP2011 普及组] 统计单词数
wanghonghui123 · · 题解
思路
-
先把两个字符串都再前后添加一个空格,方便匹配完整的单词。
-
再把所有字符都转成小写,方便操作。
-
接着用
find函数去查找,如果开始pos 就是-1 了,说明整个文章里没有指定单词,直接输出-1 。 -
否则就要开始统计单词出现的次数了,只要
pos 不等于-1 ,要一直查找。
注意
-
由于文章字符串有空格,因此要用
getline。 -
由于需要去掉多余的换行符,所以要用
getchar。
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int main(){
string c,s;
cin>>c;
getchar();
getline(cin,s);
c = ' '+c+' ';
s = ' '+s+' ';
for(int i=0;c[i];i++){
c[i] = toupper(c[i]);
}
for(int i=0;s[i];i++){
s[i] = toupper(s[i]);
}
int pos = s.find(c);
int t = pos;
if(pos==-1){
cout<<-1;
return 0;
}
int cnt = 0;
while(pos!=-1){
cnt++;
pos = s.find(c,pos+1);
}
cout<<cnt<<' '<<t<<endl;
return 0;
}