练习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;
}
}
重写你的电话号码程序,使之对多于一个电话号码的人只输出第二个和后续电话号码。
解答:
#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;
其他部分参考电话号码的实现。