Leetcode 1507. 转变日期格式
作者:互联网
给你一个字符串 date ,它的格式为 Day Month Year ,其中:
- Day 是集合 {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"} 中的一个元素。
- Month 是集合 {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"} 中的一个元素。 - Year 的范围在 [1900, 2100] 之间。
请你将字符串转变为 YYYY-MM-DD 的格式,其中:
- YYYY 表示 4 位的年份。
- MM 表示 2 位的月份。
- DD 表示 2 位的天数。
示例 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