C++primer学习:string类的练习(2)
2015-10-04 22:31
337 查看
设计一个类,它有三个unsigned成员,分别表示年月日.为其编写构造函数,接受一个表示日期的string参数,该函数应该能处理不同类型的格式,如January,1,1900 1/1/1900,Jan 1 1900,等格式
个人理解是月,日,年用某种方式分开就应该可以处理.不局限于题目给出的三种.比如1,1,1900 Jan_1_1900都可以处理.
#ifndef cp_09_1 #define cp_09_1 #include "iostream" #include "sstream" #include "fstream" #include "string" #include "deque " #include "list" #include "forward_list" #include "vector" using namespace std; const string number("123456789"); const vector<string> Month = { "January", "February", "March", "AprilMay", "May", "June", "July", "August", "September", "October", "November", "December" }; const string alpha("abcdefghijklmnopqrstuvwxyz"); class Time { public: //构造函数 Time(unsigned int y = 0, unsigned int m = 0, unsigned int d = 0) : year(y), month(m), date(m){} Time(const string &s); private: //数据结构 unsigned int month; unsigned int date; unsigned int year; unsigned select(const string & s) { size_t index = 0; for (const auto& it : Month) { ++index; if ((it.find(s)) != string::npos) break; } return index; } }; Time::Time(const string &s) { size_t pos = 0, len = 0; month = isalpha(s[0]) ? select(s.substr(0, (pos = s.find_last_of(alpha)) + 1)) : (stoi(s.substr(0, (pos = s.find_first_not_of(number) - 1) + 1))); ++pos; //计算日期 pos = s.find_first_of(number, pos);//找到日期的位置 len = s.find_first_not_of(number, pos) - pos;//找到数字的长度 date = stoi(s.substr(pos, len)); //计算年 pos = s.find_first_of(number, pos + len);//找到年的位置 len = len = s.find_first_not_of(number, pos) - pos;//找到年的长度 year = stoi(s.substr(pos, len)); } #endif
相关文章推荐
- C++primer学习:string的操作习题(1):
- CPPUTest 单元测试框架(针对 C 单元测试的使用说明)
- C++学习笔记6——类的多态
- 【小游戏】C++打造2048控制台版本
- 【小游戏】C++打造2048控制台版本
- C++构造函数以及析构函数的若干面试问题
- 《C++primer(第五版)》学习之路-第十七章:标准库特殊设施
- C#学习日记10----番外篇 C语言进制转换
- C++函数
- [C/C++]函数可变参数表
- 条款5.了解c++默默编写并且调用了哪些函数。
- C语言函数指针变量
- C++缺省参数和函数重载
- C++ assert()的用法
- 什么是EOF ,如何输入EOF
- emacs 24.4.1 终极 C++智能提示解决方案
- C++学习笔记5——类的继承
- 条款1:将c++视作一个语言联邦
- C++基础编程----2.3标准库类型vector
- C++输出格式控制