c语言以空格分割字符串_C语言: 利用sscanf() 函数分割字符串
頭文件:#include
sscanf()函數用于從字符串中讀取指定格式的數據,其原型如下:
int sscanf (char *str, char * format [, argument, ...]);
【參數】參數str為要讀取數據的字符串;format為用戶指定的格式;argument為變量,用來保存讀取到的數據。
【返回值】成功則返回參數數目,失敗則返回-1,錯誤原因存于errno 中。
sscanf()會將參數str 的字符串根據參數format(格式化字符串)來轉換并格式化數據(格式化字符串請參考scanf()), 轉換后的結果存于對應的變量中。
sscanf()與scanf()類似,都是用于輸入的,只是scanf()以鍵盤(stdin)為輸入源,sscanf()以固定字符串為輸入源。
【實例】從指定的字符串中讀取整數和小寫字母
#include
intmain()
{char str[] = "123568qwerSDDAE";char lowercase[10];intnum;
sscanf(str,"%d %[a-z]", &num, lowercase);
printf("The number is: %d\n", num);
printf("THe lowercase is: %s\n", lowercase);//===================== 分割字符串 ==========================
inta, 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: 123568THe lowercase is: qwer
a:2006, b: 3, c: 18time1:2006:03:18, time2: 2006:04:18
可以看到format參數有些類似正則表達式(當然沒有正則表達式強大,復雜字符串建議使用正則表達式處理),支持集合操作,例如:
%[a-z] 表示匹配a到z中任意字符,貪婪性(盡可能多的匹配)
%[aB'] 匹配a、B、'中一員,貪婪性
%[^a] 匹配非a的任意字符,貪婪性
另外,format不僅可以用空格界定字符串,還可以用其他字符界定,可以實現簡單的字符串分割(更加靈活的字符串分割請使用strtok()?函數)。比如上面的code:
inta, 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);
總結
以上是生活随笔為你收集整理的c语言以空格分割字符串_C语言: 利用sscanf() 函数分割字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 嚜鱼怎么做好吃呢?
- 下一篇: mysql中正则表达式的用法_Mysql