统计输入若干行的中指定的单词数量
在本文中我们以单词 the 为例
实现思路
- 调用API 获取一行字符,通过
strcmp()
判断是否输入的空格行 - 编写 函数来统计指定 单词的数量
- 不区分大小写需要将字符转换成小写,每个位置对比
代码
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
int countThe(char s[])
{
int i,count=0,len;
for(i=0;s[i]!='\0';i++){
if(s[i] !=' '){
// cout<< s[i]<<s[i+1]<<s[i+2]<<" ";
if(tolower(s[i])== 't'&& tolower(s[i+1])=='h'&& tolower(s[i+2])=='e')
count++;
}
}
return count;
}
int main()
{
char s[80];
int count=0;
cout<<"请输入字符串:(以空行结束)"<<endl;
cin.getline(s,80);
// 将输入的s字符串和 ""比较小于等于0 为false 退出
while(strcmp(s,""))
{
count+=countThe(s);
cout<<"请输入字符串:"<<endl;
cin.getline(s,80);
}
cout<<"单词the的个数为:"<<count<<endl;
return 0;
}
测试效果