最近群里有人问,char *str="aa,bb,cc,dd,ee,ff"; 怎么获取bb,cc,
一般都会想到strtok来截取字符串,然后拼接。
但是其实sscanf函数就能实现了,而且简单,一开始我用sscanf(str,"%s,%s,%s,%s,%s,%s");
发现没用,每个获取的都是aa,bb,cc,dd,ee,ff,不是单独的aa,最后发现sscanf里面可以用正则表达式,限制数字或字母,
这样才实现了这个功能。源代码如下。
#include <stdio.h>
#include <string.h>
int main()
{
char *str="ab,3d,d6,8g,fd,6h";
char temp[6][10]={{0}};
/*
sscanf(str,"%s,%s,%s,%s,%s,%s",temp[0],temp[1],temp[2],temp[3],temp[4],temp[5]);
temp[0]=ab,3d,d6,8g,fd,6h
temp[1]=ab,3d,d6,8g,fd,6h
temp[2]=ab,3d,d6,8g,fd,6h
temp[3]=ab,3d,d6,8g,fd,6h
temp[4]=ab,3d,d6,8g,fd,6h
temp[5]=ab,3d,d6,8g,fd,6h
*/
sscanf(str,"%[0-9a-zA-Z],%[0-9a-zA-Z],%[0-9a-zA-Z],%[0-9a-zA-Z],%[0-9a-zA-Z],%[0-9a-zA-Z]",
temp[0],temp[1],temp[2],temp[3],temp[4],temp[5]);
int i=0;
for(i=0;i<6;i++)
printf("temp[%d]=%s\n",i,temp[i]);
temp[0]=ab
temp[1]=3d
temp[2]=d6
temp[3]=8g
temp[4]=fd
temp[5]=6h
return 0;
}