在 C++ 中拆分 const char*

发布于 2024-10-16 08:17:37 字数 95 浏览 3 评论 0原文

我如何拆分 const char* ?

我有一个日期模式保存在 const 字符上。我想知道它是否有效。 既然我不能拆分const char*,那我该怎么办呢?

How could I split const char*?

I have a date pattern saved on a const char. I would like to know if it is valid or not.
Since I can't split const char*, what should I do then?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

嘦怹 2024-10-23 08:17:37

您可以轻松地使用 sscanf()strptime()(如果您的系统有)来解析字符缓冲区中的日/月/年字段。您还可以将文本放入 std::stringstream 中,然后将值流式传输到数字变量中,ala:

std::istringstream is("2010/11/26");
int year, month, day;
char c1, c2;
if (is >> year >> c1 >> month >> c2 >> day &&
    c1 == '/' && c2 == '/')
{
    // numeric date fields in year, month, day...
    // sanity checks: e.g. is it really a valid date?
    struct tm tm;
    tm.tm_sec = tm.tm_min = tm.tm_hour = tm.tm_wday = tm.tm_yday = tm.tm_isdst = 0;
    tm.tm_mday = day;
    tm.tm_mon = month;
    tm.tm_year = year;
    time_t t = mktime(&tm);
    struct tm* p_tm = localtime(&t);
    if (p_tm->tm_mday == day && p->tm_mon == month && p->tm_year == year)
        // survived to/from time_t, must be valid (and in range)
        do something with the date...
    else
        handle date-like form but invalid numbers...
}
else
    handle invalid parsing error...

您应该尝试一下,如果遇到困难,请发布具体问题。

You can easily use sscanf(), or perhaps strptime() if your system has it, to parse the day/month/year fields from a character buffer. You can also put the text into a std::stringstream then stream the values into numeric variables, ala:

std::istringstream is("2010/11/26");
int year, month, day;
char c1, c2;
if (is >> year >> c1 >> month >> c2 >> day &&
    c1 == '/' && c2 == '/')
{
    // numeric date fields in year, month, day...
    // sanity checks: e.g. is it really a valid date?
    struct tm tm;
    tm.tm_sec = tm.tm_min = tm.tm_hour = tm.tm_wday = tm.tm_yday = tm.tm_isdst = 0;
    tm.tm_mday = day;
    tm.tm_mon = month;
    tm.tm_year = year;
    time_t t = mktime(&tm);
    struct tm* p_tm = localtime(&t);
    if (p_tm->tm_mday == day && p->tm_mon == month && p->tm_year == year)
        // survived to/from time_t, must be valid (and in range)
        do something with the date...
    else
        handle date-like form but invalid numbers...
}
else
    handle invalid parsing error...

You should try them out and post specific questions if you have difficulties.

红玫瑰 2024-10-23 08:17:37

您应该为您的问题添加详细信息,现在它过于宽泛。一般来说,您可以使用 < code>boost::regex_match 确定给定的正则表达式是否与所有给定的字符序列匹配。

You should add details to your question, now it's overly broad. In general, you can use boost::regex_match to determine whether a given regular expression matches all of a given character sequence.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文