9-39

39.已知有如下string对象:
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;

编写程序计算sentence中有多少个单词,并指出其中最长和最短单词。如果有多个最长或最短单词,则将它们全部输出。

没看提示的时候这么写的。。能输出,但是很繁琐。。而且不知道istringstream如何重新绑定。。

#include<iostream>
#include<vector>
#include<sstream>
#include<fstream>
#include<cstdlib>
#include<list>
#include<cstring>
#include<string>
#include<deque>
using namespace std;
int main()
{
	string str2="wo ai nimen";
	string str3="ni men xingbuxing";
	string str4="buzhidao xingbu xing a";
	string line=str2+str3+str4;
	string::size_type pos=0;
	string str=" ";
    istringstream sin(line);
    string word;
    int num2=1;
    int num3=1;
    while(sin>>word)
	{
			cout<<word<<" "<<word.size()<<endl;
			if(word.size()>num2)num2=word.size();
			if(word.size()<num3)num3=word.size();
	}
	istringstream sin2(line);
	while(sin2>>word)
	{
			if(word.size()==num2)cout<<word<<"  ";
	}
	istringstream sin3(line);
	while(sin3>>word)
	{if(word.size()==num3)cout<<word<<"  ";}
	return 0;
}

41.已知有如下string对象:
string generic1(“Dear Ms Daisy:”);
string generic2(“MrsMsMissPeople”);
编写程序实现下面函数:
string greet( string form, string lastname, string title, string::size_type pos, int length );
该函数使用replace操作实现以下功能:对于字符串form,将其中的Daisy替换为lastname,将其中的Ms替换为字符串generic2中从pos下标开始的length个字符。
例如,下面的语句:
string lastName( “ AnnaP” );
string salute = greet( generic1, lastName, generic2, 5, 4 );
将返回字符串:Dear Miss AnnaP:

#include<iostream>
#include<vector>
#include<sstream>
#include<fstream>
#include<cstdlib>
#include<list>
#include<cstring>
#include<string>
#include<deque>
using namespace std;
string greet(string form, string lastname, string title,
		string::size_type pos, int length )
		{
			form.replace(8,4,lastname);
			form.replace(5,2,title,pos,length);
			return form;
		}
int main()
{
	string str2="Dear Ms Dass";
	string str3="MrsMsMissPeople";
	string lastName="AnnaP";
	cout<<greet(str2,lastName,str3,5,4)<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值