2011-02-08 138 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来确定给定的正则表达式是否与给定的字符序列的所有匹配。