其他分享
首页 > 其他分享> > Leetcode 1507. 转变日期格式

Leetcode 1507. 转变日期格式

作者:互联网

在这里插入图片描述
给你一个字符串 date ,它的格式为 Day Month Year ,其中:

请你将字符串转变为 YYYY-MM-DD 的格式,其中:

示例 1:

输入:date = "20th Oct 2052"
输出:"2052-10-20"

示例 2:

输入:date = "6th Jun 1933"
输出:"1933-06-06"

示例 3:

输入:date = "26th May 1960"
输出:"1960-05-26"

提示:

主要思路:字符串分割
Code:

class Solution {
public:
    void str_split(const std::string & src, const std::string & sep, std::vector<string> & vec_str)
    {
        std::string::size_type start = 0;
        int i=0;
        for(std::string::size_type end = src.find(sep, start); end != std::string::npos; end = src.find(sep, start))
        {
            if(end > start)
            {
                
                string str=src.substr(start, end - start);
                vec_str.push_back(str);
            }
            start = end + sep.length();
        }
        if(start < src.length())
        {
            
            string str=src.substr(start, src.length() - start);
            vec_str.push_back(str);
            
        }
    }
    string reformatDate(string date) {
        string day[]={"1st", "2nd", "3rd", "4th",
                      "5th", "6th","7th",
                      "8th", "9th","10th",
                      "11th", "12th","13th",
                      "14th", "15th","16th",
                      "17th", "18th","19th",
                      "20th", "21th","22th",
                      "23th", "24th","25th",
                      "26th", "27th","28th",
                      "29th", "30th","31st"};
        string Month []={"Jan", "Feb", "Mar",
                         "Apr", "May", "Jun",
                         "Jul", "Aug", "Sep",
                         "Oct", "Nov", "Dec"};
        
        vector<string>vec;
        str_split(date," ",vec);
        string res="";
        res+=vec[2];
        res+="-";
        for(int i=0;i<sizeof(Month)/sizeof(string);i++)
        {
            if(vec[1]==Month[i])
            {
                char str[3]={0};
                sprintf(str,"%02d",i+1);
                res+=string(str);
                res+="-";
            }
        }
        
        if(vec[0].length()==3)
        {
            
            int day=atoi(vec[0].substr(0,1).c_str());
            char str[3]={0};
            sprintf(str,"%02d",day);
            res+=string(str);
            
        }
        else
        {
            int day=atoi(vec[0].substr(0,2).c_str());
            char str[3]={0};
            sprintf(str,"%02d",day);
            res+=string(str);
        }
        return res;
        
    }
    
};

标签:std,src,string,start,1507,str,date,格式,Leetcode
来源: https://www.cnblogs.com/xiaohai123/p/16269636.html