1. 程式人生 > 實用技巧 >C語言: 利用sscanf() 函式分割字串

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\n", num);
    printf("THe lowercase is: %s\n", lowercase);    



    //===================== 分割字串  ==========================
int a, b, c; sscanf("2006:03:18", "%d:%d:%d", &a, &b, &c); printf("a: %d, b: %d, c: %d\n", 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\n", 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\n", 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\n", time1, time2);    

See:C語言sscanf()函式:從字串中讀取指定格式的資料