赞
踩
设计一个类,它有三个 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 取值范围
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。