第十七章 17.3.4节练习

练习17.24

编写你自己版本的重排电话号码格式的程序。

解答:

这个参考书中实现。


练习17.25

重写你的电话号码程序,使之只输出每个人的第一个电话号码。

解答:

#include <iostream>
#include <sstream>
#include <regex>
#include <string>

using namespace std;
using namespace std::regex_constants;

int main(){
	string str[3] = { "(201)555-2368 862-555-0123",
		"(973)555.0130",
		"(609)555-0123 2015550175 800.555-0000" };
	
	string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
	regex r(phone);
	smatch m;
	string s, first;
	string fmt = "$2.$5.$7";
	
	for (int i = 0; i != 3; ++i){
/*		cout << regex_replace(str[i], r, fmt) << endl;*/
		istringstream istr(regex_replace(str[i], r, fmt));
		istr >> first;
		cout << first << endl;
	}
}


练习17.26

重写你的电话号码程序,使之对多于一个电话号码的人只输出第二个和后续电话号码。

解答:

#include <iostream>
#include <sstream>
#include <regex>
#include <string>

using namespace std;
using namespace std::regex_constants;

int main(){
	string str[3] = { "(201)555-2368 862-555-0123",
		"(973)555.0130",
		"(609)555-0123 2015550175 800.555-0000" };
	
	string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
	regex r(phone);
	smatch m;
	string s;
	string fmt = "$2.$5.$7";
	
	for (int i = 0; i != 3; ++i){
/*		cout << regex_replace(str[i], r, fmt) << endl;*/
		string phone_num[10];
		int num = 0;
		istringstream istr(regex_replace(str[i], r, fmt));

		while(istr >> phone_num[num++]);

		if (!phone_num[1].empty()){
			for (int j = 1; j != num; ++j){
				cout << phone_num[j] << " ";
			}
			cout << endl;
		}
		else{
			cout << phone_num[0] << endl;
		}
	}
}



练习17.27

编写程序,将就为数字邮政编码的格式转化为ddddd-dddd。

解答:

string post_code = "(\\d{5})([-])?(\\d{4})?";
regex r(post_code);
string fmt = "$1-$3";
cout << regex_replace(str, r, fmt) << endl;
其他部分参考电话号码的实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值