首页 > 解决方案 > 如何从包含其他几个元素的字符串中解析和提取日期

问题描述

我在 C 中有一个字符串,我只想从中提取日期。我正在尝试使用strcat,但我认为它将日期加在一起。我不确定到底是什么问题。

我要解析的字符串是"CoursesExams=[101,28/4/2016,A;201,3/5/2016,A;110,5/5/2016;103,5/5/2016,A;120,6/5/2016,D;132,7/5/2016,B]",我只想要日期。我想要类似的东西28/4/20163/5/2016等等,但我得到的数字是 50、56、47。

    char string[1000] = "CoursesExams=[101,28/4/2016,A;201,3/5/2016,A;110,5/5/2016;103,5/5/2016,A;120,6/5/2016,D;132,7/5/2016,B]";
    int NumOEle = sizeof(string) / sizeof(char);
    char dates[1000] = "";
    int check = 0;

    for (int i = 0; i < NumOEle; i++) {
        if (string[i] == ',') {
            check++;
        }
        if (check == 1) {
            strcat(dates, string + i + 1);
            check = 0;
        }
        if (string[i] == ';') {
            check = 0;
        } else {
            continue;
        }
    }

    for (int i = 0; i < 10; i++) {
        printf("%d\n", dates[i]);
    }

    return 0;
}

标签: carraysstringdate

解决方案


可以使用直接但低效sscanf()"%n"方式来检测扫描是否成功

void printf_dates(const char *s) {
  while (*s) {
    int n = 0;
    sscanf(s, "%*2[0-9]/%*2[0-9]/%*4[0-9]%n", &n);
    // If parsing made it to the end 
    if (n > 0) {
      printf("Date <%.*s>\n", n, s);
      // To extract the day and month
      int day, month
      sscanf(s, "%d/%d", &day, &month);
      s += n;
    } else {
      s++;
    }
  }
}

用法

printf_dates("CoursesExams=[101,28/4/2016,A;201,3/5/2016,A;110,5/5/2016;103,5/5/2016,A;120,6/5/2016,D;132,7/5/2016,B]");

预期结果

Date <28/4/2016>
Date <3/5/2016>
Date <5/5/2016>
Date <5/5/2016>
Date <6/5/2016>
Date <7/5/2016>

细节:

sscanf(s, "%*2[0-9]/%*2[0-9]/%*4[0-9]%n", &n);
"%*2[0-9]"  scan but not save due to `*`, 1 to 2 characters in the set `0`-`9`
"/"  scan a '/'
"%*4[0-9]"  scan but not save due to `*`, 1 to 4 characters in the set `0`-`9`
"%n"  save into the matching `int *` argument the offset of the scan.

n仅当所有先前的扫描都成功时才更改变量。


推荐阅读