当前位置:   article > 正文

c++ primer 5th ed. practice 9.51_c++primer9.51

c++primer9.51

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

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

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

  1. #include <iostream>
  2. #include <string>
  3. #include <map> //p374关联容器
  4. struct Date {
  5. Date(const std::string &s);
  6. unsigned year;
  7. unsigned month;
  8. unsigned day;
  9. };
  10. Date::Date(const std::string &s) {
  11. //分段并获取子字符串
  12. std::map<const std::string, unsigned> mp = { //关联数组
  13. {"January", 1}, {"February", 2}, {"March", 3}, {"April", 4},
  14. {"May", 5}, {"June", 6}, {"July", 7}, {"August", 8},
  15. {"September", 9}, {"October", 10}, {"November", 11}, {"December", 12},
  16. {"Jan", 1}, {"Feb", 2}, {"Mar", 3}, {"Ari", 4},
  17. /*{"May", 5},*/ {"Jun", 6}, {"Jul", 7}, {"Aut", 8},
  18. {"Sep", 9}, {"Oct", 10}, {"Nov", 11}, {"Dec", 12},
  19. {"1", 1}, {"2", 2}, {"3", 3}, {"4", 4},
  20. {"5", 5}, {"6", 6}, {"7", 7}, {"8", 8},
  21. {"9", 9}, {"10", 10}, {"11", 11}, {"12", 12},
  22. };
  23. std::string delimiter(" ,/"); //分隔符
  24. auto pos1 = s.find_first_of(delimiter);
  25. auto pos2 = s.find_last_of(delimiter);
  26. // 注意:substr(pos,n) pos下标(索引) n大小
  27. std::string m = s.substr(0, pos1);
  28. std::string d = s.substr(pos1+1, pos2-pos1);
  29. std::string y = s.substr(pos2+1);
  30. //初始化字段 转换字符串为无字符整型 string->unsigned
  31. year = std::stoi(y);
  32. month = mp[m];
  33. day = std::stoi(d);
  34. }
  35. int main() {
  36. std::string s("January 1,1900");
  37. std::string s2("11/21/1900");
  38. std::string s3("Nov 30 1900");
  39. //输出测试
  40. std::cout << s << std::endl
  41. << " year: " << Date(s).year << std::endl
  42. << " month: " << Date(s).month << std::endl
  43. << " day: " << Date(s).day << std::endl;
  44. std::cout << s2 << std::endl
  45. << " year: " << Date(s2).year << std::endl
  46. << " month: " << Date(s2).month << std::endl
  47. << " day: " << Date(s2).day << std::endl;
  48. std::cout << s3 << std::endl
  49. << " year: " << Date(s3).year << std::endl
  50. << " month: " << Date(s3).month << std::endl
  51. << " day: " << Date(s3).day << std::endl;
  52. }

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

                字符串分隔符 delimiter 的筛选

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

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/178315
推荐阅读
相关标签
  

闽ICP备14008679号