1、前言git
本节,咱们将学习C语言库函数sscanf()的使用,使用sscanf能够快速的从复杂字符串中获取本身须要的数据。github
2、基础知识ide
1.简介函数
sscanf与scanf相似,都是用于输入的,只是后者以键盘(stdin)为输入源,前者以固定字符串为输入源。学习
2.函数描述3d
int sscanf(const char buffer, const char format, [argument]...);
参数:
buffer:须要解析的源字符串
format:窗体控件字符串,定义解析字符串的规则,能够是一个或多个
{%[*] [width] [{h | I | I64 | L}]type | ' ' | '\t' | '\n' | 非%符号}
argument:可选变量,用来存储按照format规则解析buffer的结果code
注:
(1) 亦可用于格式中, (即 %d 和 %s) 加了星号 () 表示跳过此数据。 (也就是不把此数据读入参数中)
(2) {a|b|c}表示a,b,c中选一,[d],表示能够有d也能够没有d。
(3) width表示读取宽度。
(4) {h | l | I64 | L}:参数的size,一般h表示单字节size,I表示2字节 size,L表示 4字节size(double例外),l64表示8字节size。
(5) type :这就不少了,就是%s,%d之类。
(6) 特别的:%*[width] [{h | l | I64 | L}]type 表示知足该条件的被过滤掉, 不会向目标参数中写入值,失败返回0 ,不然返回格式化的参数个数
(7) 若是读取的字符串,不是以空格来分隔的话,就可使用%[]。orm
使用时候须要包含头文件:#include<stdio.h>blog
3、基础知识字符串
1.简单用法
#include <stdio.h> char *str = "123456 hello world"; int main(void) { int num = 0; char str1[64] = { 0x00 }; char str2[64] = { 0x00 }; sscanf(str, "%d %s %", &num, str1, str2); printf("num : %d\r\nstr1 : %s\r\nstr2 : %s\r\n", num, str1, str2); return 0; }
执行结果以下:
2.取指定长度字符串
#include <stdio.h> char *str = "123456"; int main(void) { char res[64] = { 0x00 }; sscanf(str, "%4s", res); printf("res is: %s\r\n", res); return 0; }
执行结果以下:
3. * 格式使用
(*)表示跳过此数据不读入,也就是不把数据读入参数中 #include <stdio.h> int main(void) { char *str = "123456hello world"; char res[64] = { 0x00 }; char res1[64] = { 0x00 }; sscanf(str, "%*d%s %s", res, res1); printf("res is: %s\r\nres1 is: %s\r\n", res, res1); return 0; }
执行结果以下:
4. %[]格式使用
(1) 获取遇到指定字符为止的字符串
#include <stdio.h> int main(void) { char *str = "hello+world"; char res[64] = { 0x00 }; char res1[64] = { 0x00 }; sscanf(str, "%[^+]+%s", res, res1); printf("res is: %s\r\nres1 is: %s\r\n", res, res1); return 0; }
执行结果以下:
(2) 获取遇到空格为止的字符串
#include <stdio.h> int main(void) { char *str = "hello world"; char res[64] = { 0x00 }; char res1[64] = { 0x00 }; sscanf(str, "%[^ ] %s", res, res1); printf("res is: %s\r\nres1 is: %s\r\n", res, res1); return 0; }
执行结果以下:
5.取指定字符集的字符串
#include <stdio.h> int main(void) { char *str = "hello123456HELLO"; char res[64] = { 0x00 }; sscanf(str, "%[a-z1-9]", res); printf("res is: %s\r\n", res); return 0; }
执行结果以下:
4、结语
本节完,实际操做过程当中须要注意的地方有以下几点:
(1) %[^]只取到指定字符串,如继续获取以后字符串须要作处理,如上述第4小例。
这次执行不能正常获取到"world"而获取了“+world",就是因为%[^]不取该字符,使用时候须要特别注意。
2.后记:
如您在使用过程当中有任何问题,请加QQ群进一步交流,也能够github提Issue。
QQ交流群:906015840 (备注:物联网项目交流)
github仓库地址:https://github.com/solitary-sand/c
一叶孤沙出品:一沙一世界,一叶一菩提