Pack C language strings unpacking

sprintf pack

Here Insert Picture Description
Case: Thousand Feng Education

int sprintf(buf,"格式",数据)
//buf:用来存放组好的报文
//"格式":按照格式组包
//数据:各个零散的数据
返回值:返回值的是组好的报文的实际长度(不包含'\0'void test06()
{
	int year = 2020;
	int mon = 2;
	int day = 24;
	int len = 0;

	//需求:将2020 2  24组成一个"2020年2月24日"
	char buf[128]="";
	
	//%d 和 year 类型要一一对应
	len = sprintf(buf,"%d年%d月%d日", year,mon,day);
	printf("len = %d\n", len);
	printf("buf=%s\n",buf);
}

Here Insert Picture Description

sscanf unpack

Here Insert Picture Description
The basic syntax of sscanf

void test09()
{
	char buf[]="2020年2月24日";
	int year=0;
	int mon=0;
	int day=0;
	char ch = 0;
	char str_year[32]="";
	char str_mon[32]="";
	char str_day[32]="";


	//%d 只能提取'0'~'9'
	sscanf(buf,"%d年%d月%d日", &year,&mon,&day );
	printf("year = %d\n",year);//2020
	printf("mon = %d\n",mon);//2
	printf("day = %d\n",day);//24

	//%c 提取一个字符   %f 提取提取浮点数
	sscanf(buf,"%c", &ch);
	printf("##%c##\n",ch);//'2'

	//%s 提取一个字符串 遇到空格、回车、'\0' 停止获取
	//buf==>"2020年2月24日"
	sscanf(buf,"%s年%s月%s日",str_year, str_mon,str_day );
	printf("str_year=%s\n",str_year);//"2020年2月24日"
	printf("str_mon=%s\n",str_mon);//null
	printf("str_day=%s\n",str_day);//null
}

operation result:
Here Insert Picture Description

Advanced Usage sscanf 1: Use the% * s% * d (do not extract the content) extracted skip

sscanf("1234 5678","%*s %d",&data1);//5678

Advanced usage sscanf 2: Use% [n] s% [n] d extract specified data string or width n

sscanf("12345678","%*2s%2d%*2d%s" ,&data2, buf);//data2=34  buf="78";

Advanced Usage sscanf 3: Use% [az] az extracted string

//%[]都是 按 字符串 提取
char buf[128]="";
sscanf("abcDefABC","%[a-z]",buf);//遇到不是a-z的字符就跳出提取
printf("buf=%s\n", buf);//"abc"

sscanf advanced uses 4:% [aBc] extracting a B c

sscanf("aaBBcEdaBcef","%[aBc]",buf);//只提取a B c遇到其他字符也会跳出提取
printf("buf=%s\n", buf);//aaBBc

Advanced Usage sscanf 5: Use% [^ abc] abc any as long as not a must

sscanf("ABCcABC","%[^abc]",buf);//遇到a b c就会跳出提取
printf("buf=%s\n", buf);//ABC
Released three original articles · won praise 5 · Views 255

Guess you like

Origin blog.csdn.net/weixin_43288201/article/details/104526512