字符串摘取在C语言中一直具有很高的地位,以获取心知天气中的信息为例
{"results":[{"location":{"id":"WTSQQYHVQ973","name":"Nanjing","country":"CN","path":"Nanjing,Nanjing,Jiangsu,China","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},"daily":[
{"date":"2022-07-13","text_day":"Cloudy","code_day":"4","text_night":"Cloudy","code_night":"4","high":"39","low":"29",
"rainfall":"0.00","precip":"0.00","wind_direction":"W","wind_direction_degree":"270","wind_speed":"32.8","wind_scale":"5","humidity":"66"},
{"date":"2022-07-14","text_day":"Cloudy","code_day":"4","text_night":"Cloudy","code_night":"4","high":"39","low":"30",
"rainfall":"0.00","precip":"0.00","wind_direction":"W","wind_direction_degree":"270","wind_speed":"23.4","wind_scale":"4","humidity":"67"},
{"date":"2022-07-15","text_day":"Cloudy","code_day":"4","text_night":"Cloudy","code_night":"4","high":"37","low":"28",
"rainfall":"0.00","precip":"0.00","wind_direction":"NW","wind_direction_degree":"315","wind_speed":"15.3","wind_scale":"3","humidity":"71"}],
"last_update":"2022-07-13T08:00:00+08:00"}]}
当需要获取其中的日期,天气,最高温度,最低温度,以及最近更新时间等代码如下,使用C语言操作字符串指令,能够有效的获取天气,避免了使用CJSON文件包,省却了大量的代码。
char *s = NULL;
char *str[3] = {NULL,NULL,NULL};
uint32_t te = 0;
str[0] = strstr((char*)data,"date"); //摘取第一个date后的所有字符串放入str[0]
str[1] = strstr(str[0]+10,"date"); //摘取 str[0]+10 后第一个data 刚好是第二个date
str[2] = strstr(str[1]+10,"date"); //摘取 str[1]+10 后第一个data 刚好是第三个date
for(uint8_t i=0;i<3;i++){
s = strstr((char*)str[i],"date"); //
sscanf(s+7,"%[^\"]",Weather_Data[i].Date);
}
for(uint8_t i=0;i<3;i++){
s = strstr((char*)str[i],"code_day");
sscanf(s+11,"%u",&Weather_Data[i].Weather);
}
for(uint8_t i=0;i<3;i++){
s = strstr((char*)str[i],"high");
sscanf(s+7,"%u",&Weather_Data[i].Temp_H);
}
for(uint8_t i=0;i<3;i++){
s = strstr((char*)str[i],"low");
sscanf(s+6,"%u",&Weather_Data[i].Temp_L);
}
for(uint8_t i=0;i<3;i++){
s = strstr((char*)str[i],"humidity");
sscanf(s+11,"%u",&Weather_Data[i].Humi);
}
for(uint8_t i=0;i<3;i++){
s = strstr((char*)str[i],"wind_scale");
sscanf(s+13,"%u",&Weather_Data[i].Wind);
}