【问题标题】:Split const char* in C++在 C++ 中拆分 const char*
【发布时间】:2011-02-08 05:37:05
【问题描述】:

如何拆分 const char*?

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

【问题讨论】:

  • 问题含糊不清。你想从 const char * 中读取日期吗?
  • 为什么不能拆分const char*?您不能修改字符串,但您应该能够从中提取子字符串。

标签: c++ char constants string-formatting


【解决方案1】:

您可以轻松地使用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...

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 2020-08-01
      • 2022-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多