[C/C++基礎]-sscanf貪婪/非貪婪 語法教學範例

[C/C++基礎]-sscanf貪婪/非貪婪 語法教學範例

[C/C++基礎]-sscanf貪婪/非貪婪 語法教學範例


線上編譯器: https://www.tutorialspoint.com/compile_c_online.php


Code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
支援集合操作:
  %[a-z] 表示匹配a到z中任意字元,貪婪性(盡可能多的匹配)
  %[aB'] 匹配a、B、'中一員,貪婪性
  %[^a] 匹配非a的任意字元,貪婪性
*/
int main()
{
    char Info[]="Dec 12/25 School ClassRoom123456789";
    char Data1[16];
    char Data2[16];
    char Data3[50];
    sscanf(Info, "%s%s%s", Data1, Data2,Data3);//scanf 預設空格切割
    printf("Data1:%s Data2:%s Data3:%s\n", Data1, Data2, Data3);

    sscanf(Info, "%[^ ] %[^ ] %[^ ]", Data1, Data2,Data3);//正規空格切割
    printf("Data1:%s Data2:%s Data3:%s\n", Data1, Data2, Data3);

	sscanf(Info, "%s%s %[a-z A-Z]", Data1, Data2,Data3);//正規空格+英文切割
    printf("Data1:%s Data2:%s Data3:%s\n", Data1, Data2, Data3);
    
	sscanf(Info, "%s%s %[a-z A-Z 0-9]", Data1, Data2,Data3);//正規空格+[英文&數字]切割
    printf("Data1:%s Data2:%s Data3:%s\n", Data1, Data2, Data3);    
}

/*
$gcc -o main *.c -lm

$main

Data1:Dec Data2:12/25 Data3:School
Data1:Dec Data2:12/25 Data3:School
Data1:Dec Data2:12/25 Data3:School ClassRoom
Data1:Dec Data2:12/25 Data3:School ClassRoom123456789
*/

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *