• C语言: 利用sscanf() 函数分割字符串


    头文件:#include <stdio.h>

    sscanf()函数用于从字符串中读取指定格式的数据,其原型如下:

    int sscanf (char *str, char * format [, argument, ...]);

    【参数】参数str为要读取数据的字符串;format为用户指定的格式;argument为变量,用来保存读取到的数据。

    【返回值】成功则返回参数数目,失败则返回-1,错误原因存于errno 中。

    sscanf()会将参数str 的字符串根据参数format(格式化字符串)来转换并格式化数据(格式化字符串请参考scanf()), 转换后的结果存于对应的变量中。

    sscanf()与scanf()类似,都是用于输入的,只是scanf()以键盘(stdin)为输入源,sscanf()以固定字符串为输入源。

    【实例】从指定的字符串中读取整数和小写字母

    #include <stdio.h>
    
    
    int main()
    {
        
        char str[] = "123568qwerSDDAE";
        char lowercase[10];
    
        int num;
        sscanf(str, "%d %[a-z]", &num, lowercase);
        
        printf("The number is: %d
    ", num);
        printf("THe lowercase is: %s
    ", lowercase);    
    
    
    
        //===================== 分割字符串  ==========================
        int a, b, c;
        sscanf("2006:03:18", "%d:%d:%d", &a, &b, &c);
        printf("a: %d, b: %d, c: %d
    ", a, b, c);    
    
    
        char time1[20];
        char time2[20];
        sscanf("2006:03:18 - 2006:04:18", "%s - %s", time1, time2);
        printf("time1: %s, time2: %s
    ", time1, time2);    
    
        return 0;
    }

    运行结果:

    The number is: 123568
    THe lowercase is: qwer
    a: 2006, b: 3, c: 18
    time1: 2006:03:18, time2: 2006:04:18

    可以看到format参数有些类似正则表达式(当然没有正则表达式强大,复杂字符串建议使用正则表达式处理),支持集合操作,例如:
    %[a-z] 表示匹配a到z中任意字符,贪婪性(尽可能多的匹配)
    %[aB'] 匹配a、B、'中一员,贪婪性
    %[^a] 匹配非a的任意字符,贪婪性

    另外,format不仅可以用空格界定字符串,还可以用其他字符界定,可以实现简单的字符串分割(更加灵活的字符串分割请使用strtok() 函数)。比如上面的code:

    int a, b, c;
        sscanf("2006:03:18", "%d:%d:%d", &a, &b, &c);
        printf("a: %d, b: %d, c: %d
    ", a, b, c);    
    
    
        char time1[20];
        char time2[20];
        sscanf("2006:03:18 - 2006:04:18", "%s - %s", time1, time2);
        printf("time1: %s, time2: %s
    ", time1, time2);    

    See: C语言sscanf()函数:从字符串中读取指定格式的数据

  • 相关阅读:
    [编程] 正则表达式
    [游戏] PhysX物理引擎(编程入门)
    [PHP] visitFile()遍历指定文件夹
    [D3D] 用PerfHUD来调试商业游戏
    [C,C++] 妙用0元素数组实现大小可变结构体
    [D3D] DirectX SDK 2006学习笔记1——框架
    [JS] 图片浏览器(兼容IE,火狐)
    [C#(WinForm)] 窗体间传值方法
    [ASP.NET] 提示错误:The server has encountered an error while loading an application during the processing your request
    [JS] 火狐得到文件的绝对路径(暂时的方法)
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/13879828.html
Copyright © 2020-2023  润新知