C++ primer(第五版) 练习 5.14 个人code



C++ primer(第五版) 练习 5.14

题目:编写一段程序,从标准输入中读取若干 string对象并查找连续重复出现的单词。所谓连续重复出现的意思是:一个单词后面紧跟着这个单词本身。要求记录连续重复出现的最大次数以及对应的单词。如果这样的单词存在,输出重复出现的最大次数;如果不存在,输出一条信息说明任何单词没有连续出现过。例如,如果输入是:

how now now now brown cow cow

那么输出应该表明单词now连续出现了3次。


答:

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;


int main()
{
	string str = {}, tmpstr1 = {}, tmpstr2 = {};
	unsigned cnt = 0,tmpcnt=0;
	cin >> str;
	tmpstr1 = str;
	while (cin >> str)
	{
	
		if (str == tmpstr1)
		{
			++cnt;
		}
		else
		{
			if (tmpcnt < cnt)
			{
				tmpcnt = cnt;
				tmpstr2 = tmpstr1;
			}
			cnt = 1;
		}
		tmpstr1 = str;
	
	}
	if (tmpcnt == 1)
	{
		cout << "任何单词都没有连续出现过" << endl;
	}
	else
	{
		cout << tmpstr2 << "连续出现次数最多,次数为:" << tmpcnt << endl;
	}	

	return 0;
}


执行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值