C++ primer 9.39习题

#include<string>
#include<iostream>
#include<vector>
int main()
{
using namespace std;
string line1 = "We were her pride of 10 she named us:";
string line2 = "Benjamin, phoenix, the prodigal";
string line3 = "and perspicacious pacific Suzanne";
string sentence = line1 + ' ' + line2 + ' ' + line3;
string space(" ");
string::size_type pos , start, send, wordlength,ncount=0,maxlen,minlen;
pos = start = send = wordlength = 0;
vector<string> max,min;
string word;
while ((start = sentence.find_first_not_of(",:", send)) != string::npos)
{
ncount += 1;
send = sentence.find_first_of(" ", send);
if (send == string::npos)//当前处于最后一个单词
{
wordlength = sentence.size() - start;
word.assign(sentence.begin() + start, sentence.begin() + start+ wordlength);
}
else
{
if (isdigit(sentence[start]))
{
send += 1;
ncount -= 1;
continue;
}
wordlength = send - start;//单词的长度
if (ispunct(sentence[send - 1]))
wordlength -= 1;
cout << word.assign(sentence.begin() + start, sentence.begin() + start+ wordlength) << endl;
send += 1;
}


if (ncount == 1)
{
maxlen = minlen = wordlength;
max.push_back(word);
min.push_back(word);
}


if (wordlength > maxlen)
{
maxlen = wordlength;
max.clear();
max.push_back(word);
}
else if (wordlength == maxlen)
max.push_back(word);


if (wordlength < minlen)
{
minlen = wordlength;
min.clear();
min.push_back(word);
}
else if (wordlength == minlen)
min.push_back(word);


}


printf("有%d个单词!\n", ncount);
vector<string>::iterator itermax = max.begin();
cout << "单词最长的有:\n";
while (itermax!=max.end())
{
cout << *itermax++ << " ";
}
cout << endl;
cout << "单词最短的有:\n";
vector<string>::iterator itermin = min.begin();
while (itermin != min.end())
{
cout << *itermin++ << " ";
}
cout << endl;
system("pause");
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值