C++ primer 第五版 中文版 练习 9.49 个人code

C++ primer 第五版 中文版 练习 9.49

题目:如果一个字母延伸到中线之上,如d或f,则称其有上出头部分(ascender)。
如果一个字母延伸到中线之下,如p或g,则称其有下出头部分(descender)。
编写程序,读入一个单词文件,输出最长的既不包含上出头部分,也不包含下出头部分的单词。

答:

/*
如果一个字母延伸到中线之上,如d或f,则称其有上出头部分(ascender)。
如果一个字母延伸到中线之下,如p或g,则称其有下出头部分(descender)。
编写程序,读入一个单词文件,输出最长的既不包含上出头部分,也不包含下出头部分的单词。
*/

#include <iostream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;

//既不包含上出头分部,也不包含下出头部分的单词
vector<string> find_noasd_nodesd(const vector<string> &svect)
{
	vector<string> newvect;
	// abcdefghijklmnopqrstuvwxyz
	string ascender("bdfhklt"); //上出头部分单词
	string descender("gjpqy");  //下出头部分单词
	auto &b = svect.begin();
	
	while (b != svect.end())
	{

		if (b->find_first_of(ascender) == string::npos && b->find_first_of(descender) == string::npos)
			newvect.push_back(*b);

			++b;
	}
	
	return newvect;
}

//查找长度最长的字符串
string find_maxlen_string(const vector<string> &svect)
{
	string maxstr;
	auto &b = svect.begin();
	while (b < svect.end()-1)
	{
		if ((*b).size() > (*(b + 1)).size())
			maxstr = *b;
		else
			maxstr = *(b + 1);
		++b;
	}
	return maxstr;
}

int main()
{
	//读取文本文件
	fstream myfstream;
	myfstream.open("test.txt", ios::in);
	string tmpstr;
	vector<string> word;
	if (myfstream)
	{
		while (!myfstream.eof())
		{
			myfstream >> tmpstr;
			word.push_back(tmpstr);
		}
	}


	vector<string> noasd_nodesdvect; //不包含出头部分的单词
	string maxlenstring; //最长的单词
	noasd_nodesdvect = find_noasd_nodesd(word);
	maxlenstring = find_maxlen_string(noasd_nodesdvect);
	cout << "既不包含上出头部分,也不包含下出头部分的单词为:" << endl;
	for (auto a : noasd_nodesdvect)
		cout << a << " ";
	cout << endl;
	cout << "最长的单词为:";
	cout << maxlenstring << endl;

	return 0;

}

我用来测试的文件内容如下:

he lamv is a vertical take-off and landing aircraft that can fly in a quick, quiet, and agile manner.it is a new type of vehicle that combines the speed of an airplane and the vertical take-off capability of a helicopter with some characteristics of a ground vehicle, but without the limitations of any of those existing modes of transportation.

执行结果:




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值