简体   繁体   中英

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM