c++ primer 习题9.39

发现配套的习题答案有问题,稍作修改,得到正确的结果

int main()
{
	string line1="We were her pride of 10 she named us:";
	string line2="Benjamin, phoenux, the Prodigal";
	string line3="and perspicacicous pacific Suzanne";
	string sentence=line1+' '+line2+' '+line3;
	string separators(" \t:,\v\r\n\f");//用作分隔符的字符
    string word;
    vector<string> maxv, minv;//存放最长及最短单词的vector容器
    string::size_type max_len,min_len,len,count=0;//sentence中最长、最短单词以及下一单词的长度,单词数目
    string::size_type start_pos=0,end_pos=0;//单词的起始及结束位置
 
	start_pos=sentence.find_first_not_of(separators,end_pos);
    while(start_pos!=string::npos){
		count++;//统计单词的个数
		end_pos=sentence.find_first_of(separators,start_pos);//找到下一处分隔符
		if(end_pos==string::npos){//找到的是最后一个单词
			len=sentence.size()-start_pos;
		}
		else {
			len=end_pos-start_pos;
		}
		word.assign((sentence.begin()+start_pos),(sentence.begin()+start_pos+len));//用了string的assign函数:c.assign(b,e),b/e为迭代器
		if(count==1){//以第一个单词为容器赋初值
			max_len=min_len=len;
			maxv.push_back(word);
			minv.push_back(word);
		}
		else{
			if(len>max_len){
				max_len=len;
				maxv.clear();
				maxv.push_back(word);
			}
			else if(len==max_len){
				maxv.push_back(word);
			}
			if(len<min_len){
				min_len=len;
				minv.clear();
				minv.push_back(word);
			}
			else if(len==min_len){
				minv.push_back(word);
			}
		}
		start_pos=sentence.find_first_not_of(separators,end_pos);//找到下一处单词的开始
	}
 
    //输出单词数目
    cout << "word amount:" << count << endl;
    vector<string>::iterator iter;
    //输出最长单词
    cout << "longest word(s):" << endl;
    iter = maxv.begin();
    while(iter != maxv.end())
        cout << *iter++ << endl;
    //输出最短单词
    cout << "shortest word(s):" << endl;
    iter = minv.begin();
    while(iter != minv.end())
        cout << *iter++ << endl;
	system("pause");
	return 0;
}
运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值