【发布时间】:2022-01-28 20:46:12
【问题描述】:
好的,所以我在 StackOverflow 上环顾四周,偶然发现了一种通过分隔符拆分 C++ 的方法。
到目前为止,我都看了这些,还是没看懂。
- Parse (split) a string in C++ using string delimiter (standard C++)
- https://www.oreilly.com/library/view/c-cookbook/0596007612/ch04s07.html
- C++ spliting string by delimiters and keeping the delimiters in result
- split a C++ string into two integers, which are delimited by ":"
根据我的理解,我需要使用分隔符,使用包含分隔符的变量,然后使用substr() 方法/函数,但我不明白整个事情。
例如,我看到一个引用pos 和npos 的示例,我不明白这一点。我的另一个问题是,我不知道如何处理具有多个相同分隔符副本的字符串。
我的目标是采用这样的日期:"29/01/2022 • 05:25:01" 将其拆分为日期和时间的结构,例如:
struct Date
{
int day; //Integer for days
int month; //Integer for months
int year; //Integer for years
};
struct Time
{
int hour; //Integer for hour of drop
int minute; //Integer for minute of drop
int second; //Integer for second of drop
int milisecond; //Integer for milisecond of drop
};
我也看过https://www.cplusplus.com/reference/,但是我想将其拆分,以便将它们存储在自己的变量中,例如:
string example
{
struct Date D;
struct Time T;
D.Day = 29;
D.Month = 01;
D.Year = 2022;
T.Hour = 5;
T.Minute = 25;
T.Second = 01;
}
有人能以更简单的方式向我解释这一点,或者向我展示一个更容易解释的来源吗?我的主要问题是不理解某些单词。
感谢任何帮助,我真的在努力学习,但我还不太了解这些主题。
【问题讨论】:
-
您的问题并不完全清楚-您的问题是关于按分隔符拆分字符串,但您在此处显示的代码甚至没有尝试这样做。此外,您的
string example代码甚至无法编译 - 您是否尝试使用Date D和Time T初始化example? -
看看
std::get_time(),它允许您自定义解析来自任何std::istream的日期/时间值。例如,您可以将字符串放入std::istringstream中,然后对其进行解析。
标签: c++ date struct split delimiter