Count the number of words specified in several lines of input
In this article we take the word the as an example
Implementation ideas
- Call the API to get a line of characters, and
strcmp()
determine whether there is an input blank line - Write a function to count the number of specified words
- Case insensitivity requires converting characters to lowercase and comparing each position
code
#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;
}
Test effect