2011-02-08 140 views
0

如何拆分const char *?在C++中分割const char *

我有一個日期模式保存在一個常量字符。我想知道它是否有效。 因爲我不能分解const char *,那麼我應該怎麼做?

+0

`std :: string`是一個選項嗎? – 2011-02-08 05:38:21

回答

2

如果您的系統具有此功能,可以使用sscanf()strptime()來解析字符緩衝區中的日/月/年字段。你也可以把文字變成一個std :: stringstream的則流值成數值變量,鼻翼:

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

你應該嘗試出來和後期的具體問題,如果你有困難。

1

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