我有一个字符串“YYYY-MM-DD”,我想将该字符串转换为整数并将它们分别存储为年、月、日。我使用 substr
得到了 year 但我无法得到 MM 和 DD。
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int dayOfYear(string date)
{
for (int i = 0; i < date.size(); i++)
{
if (date[i] == '-')
date.erase(date.begin()+i);
}
//getting substring for year
string str1 = date.substr(0, 4);
string str2 = date.substr(5, 6);//getting wrong output
//converting string to int
int year = stoi(str1);
int month = stoi(str2);
return month;//getting output as 109
}
int main()
{
string date = "2019-01-09";
int p = dayOfYear(date);
cout << p;
return 0;
}
最佳答案
您没有正确使用 std::string::substr()
。你给了它两个索引(而且是错误的索引),但它需要一个索引和一个计数。
没有必要 erase()
-
字符(此外,你的循环无论如何都被打破了,因为你没有重新调整 i
在每个 erase()
之后,因此您正在跳过字符)。您可以使用 std::string::find()
找到 -
字符的索引,然后使用这些索引计算 std 所需的值::string::substr()
.
int yearOfDate(std::string date)
{
size_t ends = date.find('-');
//getting substring for year string
string str = date.substr(0, end);
//converting string to int
return std::stoi(str);
}
int monthOfDate(std::string date)
{
size_t start = date.find('-') + 1;
size_t end = date.find('-', start);
//getting substring for month string
string str = date.substr(start, end - start);
//converting string to int
return std::stoi(str);
}
int dayOfDate(std::string date)
{
size_t start = date.find('-');
start = date.find('-', start + 1) + 1;
//getting substring for day string
string str = date.substr(start);
//converting string to int
return std::stoi(str);
}
int main()
{
string date = "2019-01-09";
int y = yearOfDate(date);
int m = monthOfDate(date);
int d = dayOfDate(date);
std::cout << y << ' ' << m << ' ' << d;
return 0;
}
由于您使用的是 C++11 或更高版本(通过使用 std::stoi()
),请考虑使用 std::get_time()
相反:
#include <sstream>
#include <iomanip>
#include <ctime>
int main()
{
string date = "2019-01-09";
std::tm t = {};
std::istringstream(date) >> std::get_time(&t, "%Y-%m-%d");
int y = tm.tm_year + 1900;
int m = tm.tm_mon + 1;
int d = tm.tm_mday;
std::cout << y << ' ' << m << ' ' << d;
return 0;
}
在 C++20 中,您可以使用 std::chrono::from_stream(std::chrono::year_month_day)
相反:
#include <sstream>
#include <chrono>
int main()
{
string date = "2019-01-09";
std::istringstream iss(date);
std::chrono::year_month_day ymd;
std::from_stream(iss, "%Y-%m-%d", ymd);
unsigned y = ymd.year();
unsigned m = ymd.month();
unsigned d = ymd.day();
std::cout << y << ' ' << m << ' ' << d;
return 0;
}
关于c++ - 如何从字符串中间提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57447190/