开发者

Split const char* in C++

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开发者_C百科 can't split const char*, what should I do then?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜