c - 如何从包含其他几个元素的字符串中解析和提取日期
问题描述
我在 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/2016
,3/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;
}
解决方案
可以使用直接但低效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
仅当所有先前的扫描都成功时才更改变量。
推荐阅读
- bash - 根据bash / posh中数组中的列匹配值将CSV拆分为两个文件
- python-3.x - 如何用鼠标绘制并保存为 1 和 0
- javascript - 如何在 SharePoint 文档库中的一组选定电子表格中进行人员搜索并返回这些行
- c# - 在 C# 中按可变长度拆分字符串时的正则表达式拆分行为
- powershell - PowerShell 属性表达式将执行时间增加 4-5 倍
- unity3d - 考虑到初始对象的前向角,找到 2 个对象之间的航向角
- javascript - 对视图中的组件的操作
- splunk - 替代子搜索来搜索超过百万个条目
- c# - 处理前后的 C# WPF 更新标签 - 立即
- reactjs - 尝试禁用后,React 应用程序中的 eslint 错误仍然存在