您的位置:首页 > 编程语言 > C语言/C++

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: