You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用sscanf解析含分隔符的时间字符串?如何提取T后的子串?

处理ISO格式日期时间字符串的两种高效方法

嘿,这个场景我太熟悉了!咱们分别解决你提到的两个问题:

用sscanf解析带分隔符的日期时间字符串

你完全可以直接把那些分隔符(-、T、:、.)写进sscanf的格式字符串里——sscanf会自动识别这些非格式符,要求输入字符串对应位置必须匹配,然后跳过它们继续解析数值。

针对你的YYYY-MM-DDTHH:MM:SS.sss格式,格式串可以这么写:"%d-%d-%dT%d:%d:%d.%d"。直接把各个字段的变量地址传进去就行,示例代码如下:

#include <stdio.h>

int main() {
    const char *datetime_str = "2013-04-20T13:50:47.390";
    int year, month, day, hour, minute, second, millisec;
    
    // 解析所有7个字段
    int parsed_count = sscanf(datetime_str, "%d-%d-%dT%d:%d:%d.%d",
                           &year, &month, &day, &hour, &minute, &second, &millisec);
    
    if (parsed_count == 7) { // 确认所有字段都成功匹配
        printf("日期:%d年%d月%d日\n", year, month, day);
        printf("时间:%d:%d:%d.%d\n", hour, minute, second, millisec);
    } else {
        printf("解析失败,可能是字符串格式不匹配\n");
    }
    return 0;
}

这种方式既简洁又高效,完全符合你想用sscanf的需求。

高效截取'T'之后的时间部分

最省资源且高效的方法是用标准库的strchr函数——它专门用来查找字符串中某个字符的首次出现位置,底层是优化过的,速度很快。

有两种思路:

  1. 直接使用指针(零复制):找到'T'的位置后,直接用t_pos + 1作为指向时间部分的指针(前提是原字符串不会被修改),连内存复制都省了:
#include <stdio.h>
#include <string.h>

int main() {
    const char *datetime_str = "2013-04-20T13:50:47.390";
    const char *t_sep = strchr(datetime_str, 'T');
    
    if (t_sep != NULL) {
        printf("截取的时间部分:%s\n", t_sep + 1); // 直接输出T之后的内容
    } else {
        printf("字符串中未找到分隔符'T'\n");
    }
    return 0;
}
  1. 复制到新字符串:如果需要把时间部分存到独立的字符串里,用strcpy配合t_pos + 1即可:
#include <stdio.h>
#include <string.h>

int main() {
    const char *datetime_str = "2013-04-20T13:50:47.390";
    char time_part[20]; // 确保数组大小足够容纳时间部分
    const char *t_sep = strchr(datetime_str, 'T');
    
    if (t_sep != NULL) {
        strcpy(time_part, t_sep + 1);
        printf("存储的时间部分:%s\n", time_part);
    } else {
        printf("字符串中未找到分隔符'T'\n");
    }
    return 0;
}

两种方法都很高效,优先选第一种零复制的方式,除非你需要独立的字符串副本。

内容的提问来源于stack exchange,提问作者Pedro Lima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:51:15