記事は複数行あり、空行を入力終了条件としています。記事内の単語 (大文字と小文字に関係なく、単語はスペースで区切られています) の数を数えます (C++ 演習)

数行の入力で指定された単語の数をカウントします。

この記事では、単語を例として取り上げます

実装のアイデア
  • 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