统计单词数
题意
统计出特定单词在文章中出现的次数
思路
- 输入两个字符串后对他们进行大小写转化
- 在for循环中对字符串进行处理
- 输出结果即可
坑点
注意大小写的转化
实现步骤
同思路
代码
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
int main(){
string s1,s2,ans;
int count=0,position=-1; //定义计数器和初识位置
getline(cin,s1);
getline(cin,s2);
transform(s1.begin(),s1.end(),s1.begin(),::tolower);
transform(s2.begin(),s2.end(),s2.begin(),::tolower);
s2.insert(s2.end(),' ');//strcat(s2,' ');//在s2后面添加空格
for(int i=0;i<s2.length();i++){
if(s2[i]!=' '){
ans+=s2[i];
}
else{
if(ans==s1){
if(position==-1){
position=i-s1.length();
}
count++;
}
ans.clear();
}
}
if(count>0){
printf("%d %d",count,position);
}
else{
printf("%d",position);
}
return 0;
}
总结
字符串输入输出