长字符串的解析可通过sscanf函数进行信息提取
- %[^:] 截取字符到:
- %*[^:]截取字符到:但忽略该部分数据
示例:
void test(void){
const char *str = " today is 2021.8.5";
int year = 0;
int month = 0;
int day = 0;
sscanf(str, " today is %d.%d.%d\n", &year, &month, &day);
printf("year:%d,month:%d,day:%d\n", year, month, day);
}
void test2(void){
const char *str = "5.0 www. baidu: com:80";
char addr[64] = "";
char addr2[64] = "";
int port = 0;
double data = 0;
sscanf(str, "%lf %[^:]:%[^:]:%d", &data,addr, addr2, &port);
printf("data:%lf,addr:%s,addr2:%s,port:%d\n", data,addr, addr2, port);
}
void test3(void)
{
const char *str = "$GNRMC,122981.000,A,3204.882246,N,11854.9911047,E,0.099,191.76,280521,,E,A*00";
char valid = ' ';
double longitude = 0;
double latitude = 0;
char laa[64] = "";
sscanf(str, "$GNRMC,%[^,],%c,%lf,%*c,%lf,%*c,", laa, &valid, &latitude, &longitude);
printf("laa:%s,volid:%c,longitude:%f,latitude:%f\n", laa, valid, longitude, latitude);
}
void test4(void){
const char *str = "V:1.178,1.182,7.463,3.168,1.788,-5.006 MA:0.50,31.52,20.02,6.50,13.32,-21.38 UA:0.0,0.0,0.0,0.0,0.0,0.0 Alar";
double avdd,iovcc,vci,pvdd,pvee,dvdd;
double avddi, iovcci, vcii, pvddi, pveei, dvddi;
sscanf(str, "V:%lf,%lf,%lf,%lf,%lf,%lf %*[^:]:%lf,%lf,%lf,%lf,%lf,%lf", &avdd, &iovcc, &vci, &pvdd, &pvee, &dvdd,
&avddi,&iovcci, &vcii, &pvddi, &pveei, &dvddi);
printf("V:%lf,%lf,%lf,%lf,%lf,%lf,MA:%lf,%lf,%lf,%lf,%lf,%lf\n", avdd, iovcc, vci, pvdd, pvee, dvdd,
avddi, iovcci, vcii, pvddi, pveei, dvddi);
}
int main()
{
test();
test2();
test3();
test4();
return 0;
}
结果如下:
year:2021,month:8,day:5
data:5.000000,addr:www. baidu,addr2: com,port:80
laa:122981.000,volid:A,longitude:11854.991105,latitude:3204.882246
V:1.178000,1.182000,7.463000,3.168000,1.788000,-5.006000,MA:0.500000,31.520000,20.020000,6.500000,13.320000,-21.380000
部分code截取自rtthread物联网操作系统官方公众号
|