1.api查找
- c语言API参考:https://cplusplus.com/reference/,解析语句需要用到strstr函数。该函数位于string.h
头文件中。



2.实现功能
- 利用strstr函数将语句中的关键词查找并定位到,并将参数存储于结构体中。
#include <stdio.h>
#include <string.h>
typedef struct info {
char version[32];
char product[32];
unsigned char versionS;
unsigned char productS;
}Info;
int stringToCharArray(char* lineBuf, char* dst, int maxSize, char* s)
{
char* pos1 = strstr(lineBuf, s);
char* pos2 = strstr(lineBuf, "=");
char* pos3 = strstr(lineBuf, ";");
char line[64];
memset(line, 0, 64);
int len = pos3 - (pos2 + 1);
if (pos1 != NULL && pos2 != NULL && pos3 != NULL && pos3 > (pos2 + 1)) {
strncpy_s(line, pos2 + 1, pos3 - (pos2 + 1));
if (len <= 32) {
memcpy(dst, line, len);
dst[len] = '\0';
}
else {
printf("string is too long");
return -1;
}
}
else {
return -1;
}
return 0;
}
int main()
{
char str1[] = "version = B_1023_01;";
char str2[] = "product = BenChi;";
Info info;
memset(&info, 0, sizeof(Info));
if (stringToCharArray(str1, info.version, 32, (char*)"version")==0) {
printf("version=%s\n", info.version);
info.versionS = 1;
}
else {
printf("version get failed\n");
}
if (stringToCharArray(str2, info.product, 32, (char*)"product") == 0) {
printf("product=%s\n", info.product);
info.productS = 1;
}
else {
printf("product get failed\n");
}
return 0;
}
----------------代码输出----------------
version= B_1023_01
product= BenChi