C++primer学习:string类的练习(2)

设计一个类,它有三个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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值