簡體   English   中英

在C ++中分割const char *

[英]Split const char* in C++

如何分割const char *?

我有一個保存在const char上的日期模式。 我想知道它是否有效。 由於我無法拆分const char *,那么該怎么辦?

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

如果遇到困難,您應該嘗試一下並發布特定問題。

您現在應該為問題添加詳細信息,因為它過於廣泛。 通常,您可以使用boost::regex_match來確定給定的正則表達式是否與所有給定的字符序列匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM