C 库函数 int sscanf(const char *str, const char *format, ...) 从字符串读取格式化输入.
函数返回转换成功的个数;
用法直接贴代码;
一般用法:
int main()
{
// 一般用法:
char buf[64] = {0};
sscanf("abcdefg ", "%s", buf);
printf("%s\n", buf);
// 输出 abcdefg
return(0);
}
按长度截取字符串:
注意是从左侧开始计算长度,并且当不足截取的长度将全部保留;
int main()
{
// 按长度截取:
char buf[64] = {0};
sscanf("abcdefg ", "%4s", buf);
printf("%s\n", buf);
// 输出 abcd
return(0);
}
取仅包含指定字符集的字符串:取仅包含1到9和小写字母的字符串
注意:当字符串中遇到第一个非集合内的字符,则停止截取,如下只会输出“123456abcdedf” 大写字符“BCDEF”后的“xyz”不会放到buf中;
%[a-z] 表示匹配a到z中任意字符
%[aB'] 匹配a、B、'中一员
%[^a] 匹配非a的任意字符,并且停止读入
int main()
{
// 取仅包含指定字符集的字符串:取仅包含1到9和小写字母的字符串
char buf[64] = {0};
sscanf("123456abcdedfBCDEFxyz", "%[1-9a-z]", buf);
printf("%s\n", buf);
// 输出 123456abcdedf
return(0);
}
从字符串读取格式化输入.;
include <string.h>
int main()
{
int day, year,icount;
char weekday[20], month[20], dtm[100];
strcpy( dtm, "Saturday May 27 2021" );
icount = sscanf( dtm, "%s %s %d %d", weekday, month, &day, &year );
// 成功转换四个,icount为4;
printf("%s %d, %d = %s\n", month, day, year, weekday );
// 输出:May 27 2021 = Saturday
return(0);
}
其他用法:
%*s表示第一个匹配到的%s被过滤掉
比如:
int main()
{
char buf[512] = {0};
sscanf("hello, world", "%*s%s", buf);
printf("%s\n", buf);
// 输出 world
return(0);
}