c++ primer 5th ed. practice 9.51

设计一个类,它有三个 unsigned 成员,分别表示年,月,日。

为其编写构造函数,接受一个表示日期的 string 参数。

你的构造函数应该能处理不同数据格式,如 January 1,1900 1/1/1900 Jan 1 1900 等。

 #include <iostream>
 #include <string>
 #include <map> //p374关联容器
 
 struct Date {
 
     Date(const std::string &s);
     unsigned year;
     unsigned month;
     unsigned day;
 };
 
 Date::Date(const std::string &s) {

     //分段并获取子字符串
     std::map<const std::string, unsigned> mp = {       //关联数组
 
         {"January", 1}, {"February", 2}, {"March", 3}, {"April", 4},
         {"May", 5}, {"June", 6}, {"July", 7}, {"August", 8},
         {"September", 9}, {"October", 10}, {"November", 11}, {"December", 12},
         {"Jan", 1}, {"Feb", 2}, {"Mar", 3}, {"Ari", 4},
         /*{"May", 5},*/ {"Jun", 6}, {"Jul", 7}, {"Aut", 8},
         {"Sep", 9}, {"Oct", 10}, {"Nov", 11}, {"Dec", 12},
         {"1", 1}, {"2", 2}, {"3", 3}, {"4", 4},
         {"5", 5}, {"6", 6}, {"7", 7}, {"8", 8},
         {"9", 9}, {"10", 10}, {"11", 11}, {"12", 12},
     };
     std::string delimiter(" ,/");                 //分隔符
     auto pos1 = s.find_first_of(delimiter);
     auto pos2 = s.find_last_of(delimiter);
     // 注意:substr(pos,n) pos下标(索引) n大小
     std::string m = s.substr(0, pos1);
     std::string d = s.substr(pos1+1, pos2-pos1);
     std::string y = s.substr(pos2+1);
     //初始化字段 转换字符串为无字符整型 string->unsigned
     year = std::stoi(y);
     month = mp[m];
     day = std::stoi(d);
 }
 
 int main() {
     
     std::string s("January 1,1900");
     std::string s2("11/21/1900");
     std::string s3("Nov 30 1900");
     //输出测试
     std::cout << s  << std::endl
             << " year: " << Date(s).year << std::endl
             << " month: " << Date(s).month << std::endl
             << " day: " << Date(s).day << std::endl;
     std::cout << s2  << std::endl
             << " year: " << Date(s2).year << std::endl
             << " month: " << Date(s2).month << std::endl
             << " day: " << Date(s2).day << std::endl;
     std::cout << s3  << std::endl
             << " year: " << Date(s3).year << std::endl
             << " month: " << Date(s3).month << std::endl
             << " day: " << Date(s3).day << std::endl;
 }

关键在于 关联数组 map<const string, unsigned> 的建立

                字符串分隔符 delimiter 的筛选

                查找定位分隔符 find_first_of() find_last_of()

               子字符串函数 substr(pos, n) 

特别注意 pos 下标(索引)和 n 取值范围

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值