一篇文章有若干行,以空行作为输入结束的条件。统计一篇文章中的单词the(不管大小写,单词,the是由空格隔开的)的个数(C++习题)

统计输入若干行的中指定的单词数量

在本文中我们以单词 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;
}


测试效果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45833112/article/details/127322299