作业帮 > 综合 > 作业

字符串中提取年月日,year、month、day,格式:year=2012,month=march-April、day=

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/04/29 23:41:48
字符串中提取年月日,year、month、day,格式:year=2012,month=march-April、day=6-8
string date("Jan.30 2012-Feb.2 2012");
string date("Jan.30-Feb.2 2012");
string date("30 March-3 April 2003");
string date("6-8 May 2012");
string date("12 April 2012");
string date("Nov/Dec.12 2012");
string date("April 12 2012");
string date("April 2012");
string date("2012");
比较繁.
先找有无 - 或 /, 有则分为2 个部分,无, 则是 1个部分.
然后 把两部分 的 字符串 抓出来.
字符串判断,字母开始 是 月,其它,4个数字是年,余下是 日.
用C++找 - 或 / :
size_t pos=0; pos = str.find("-");
if (pos==0) pos = str.find("/");

用C:
string str("Jan. 30 2012-Feb. 2 2012");
int main ()
{
int i;
int found= -1;
char s1[3][10],s2[3][10];
int n1=0,n2=0;
char cstr[40],c1[40],c2[40];

strcpy (cstr, str.c_str());
for (i=0;i < str.length(); i++) if ( cstr[i]=='-' || cstr[i]=='/') {
found = i; cstr[i]=' ';
}
if (found > 0) {
strcpy(c1,cstr); c1[found]='\0';
n1 = sscanf(c1,"%s %s %s",s1[0],s1[1],s1[2]);
strcpy(c2, &cstr[found+1]);
n2 = sscanf(c2,"%s %s %s",s2[0],s2[1],s2[2]);
} else{
n1 = sscanf(cstr,"%s %s %s",s1[0],s1[1],s1[2]);
}
前1 部分 的 字符串 在 s1[0],s1[1],s1[2] 中,年月日个数为 n1
后1 部分 的 字符串 在 s2[0],s2[1],s2[2] 中, 年月日个数为 n2
然后循环判断一下即可
取出的字符串是否正确,可以临时打印出来看:
for (i=0;i