1. 需求
当前待解析字符串格式为:
+CIFSR:STAIP,<Station IP address>
+CIFSR:STAMAC,<Station MAC address>
某次通信具体的数据内容为:
+CIFSR:STAIP,"0.0.0.0"
+CIFSR:STAMAC,"98:f4:ab:da:a6:7f"
要从中提取出ip地址目标字符串[0.0.0.0]。
2. 实现方法
① 利用strstr找到固定头部;
② 利用sscanf提取具体数值;
3. 实现代码
#include <stdio.h>
#include <string.h>
char src_str[100] = "+CIFSR,STAIP:\"122.51.89.94\"\r\n";
int seg1,seg2,seg3,seg4;
int main(void)
{
char hostip[15];
char *str = strstr(src_str, "STAIP");
printf("str is [%s]\r\n", str);
sscanf(str+strlen("STAIP:"), "\"%d.%d.%d.%d\"", &seg1, &seg2, &seg3, &seg4);
sprintf(hostip, "%d.%d.%d.%d", seg1, seg2, seg3, seg4);
if (!hostip) {
printf("parser fail\r\n");
} else {
printf("parser success, host ip is:%s\r\n", hostip);
}
return 0;
}
编译:
gcc test.c -o test.exe
执行: