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.
执行结果: