项目开发考试题目——20200210

本文介绍了一个用于从键值对(key=value)字符串中解析并去除空格的C语言程序。该程序定义了接口以根据键获取值,并通过测试用例验证其正确性。

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

代码如下:

/*==================================================================================
键值对("key = value")字符串,在开发中经常使用;
要求1:请自己定义一个接口,实现根据key获取value;
要求2:编写测试用例;
要求3:键值对中间可能有n多空格,请去除空格.
注 意:键值对字符串格式可能如下:
"key1 = value1"
"key2 =    value2  "
"key3  = value3"
"key4        = value4"
"key5   =   "
"key6   ="
"key7   =   "
==================================================================================*/

#define  _CRT_SECURE_NO_WARNINGS 
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>

int trimspace(char* inbuf, char* outbuf)
{
	int ret = 0;
	int ncount = 0;
	if (inbuf == NULL)
	{
		ret = -1;
		printf("func trimspace() NULL error:%d\n", ret);
		return ret;
	}
	char* p1 = inbuf;
	int i = 0;
	int j = strlen(p1) - 1;
	while (isspace(p1[i]) && p1[i] != '\0')
	{
		i++;
	}
	while (isspace(p1[j]) && p1[j] != '\0')
	{
		j--;
	}
	ncount = j - i + 1;
	strncpy(outbuf, p1 + i, ncount);
	return ret;
}

int getkeybyvalue(char* keyvalue, char* keybuf, char* valuebuf, int* valuelen)
{
	int ret = 0;
	//1.查找字符串中是否存在key
	if (keyvalue == NULL || keybuf == NULL || valuebuf == NULL || valuelen == NULL)
	{
		ret = -1;
		printf("func NULL error:%d\n", ret);
		return ret;
	}
	char* p = keyvalue;
	p = strstr(p, keybuf);
	if (p == NULL)
	{
		ret = -1;
		printf("No key char error:%d\n", ret);
		return ret;
	}
	p = p + strlen(keybuf);
	//2.查找字符串中是否存在"="
	p = strstr(p, "=");
	if (p == NULL)
	{
		ret = -1;
		printf("No = char error:%d\n", ret);
		return ret;
	}
	p = p + strlen("=");
	//3.去除字符串前后的空格
	ret = trimspace(p, valuebuf);
	if (ret != 0)
	{
		printf("func trimspace error:%d\n", ret);
		return ret;
	}
	*valuelen = strlen(valuebuf);
	return ret;
}

int main()
{
	int ret = 0;
	char* keyandvalue = "key2 =    value2  ";
	char keybuf[16] = "key2";
	char valuebuf[64] = { 0 };
	int valuelen = 0;
	ret = getkeybyvalue(keyandvalue, keybuf, valuebuf, &valuelen);
	if (ret != 0)
	{
		printf("func getkeybyvalue() error:%d\n", ret);
	}
	printf("valuebuf=%s\n", valuebuf);
	printf("valuelen=%d\n", valuelen);
	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值