c语言strstr解析定位字符串并存储在结构体中

本文介绍了如何使用C语言中的strstr函数从字符串中查找子串。通过示例代码展示了如何解析包含特定关键词的语句,并将这些信息存储到结构体中,从而实现数据提取。代码成功地从给定的字符串中提取了`version`和`product`信息,并将其分别输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.api查找

  • c语言API参考:https://cplusplus.com/reference/,解析语句需要用到strstr函数。该函数位于string.h
    头文件中。
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

2.实现功能

  • 利用strstr函数将语句中的关键词查找并定位到,并将参数存储于结构体中。
/* strstr example */
#include <stdio.h>
#include <string.h>

/*
* version = zc08A;
* product = m256;
* 解析目标语句,存储在结构体中
*/
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alex1_Code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值