项目开发考试题目——20200210

代码如下:

/*==================================================================================
键值对("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;
}
发布了140 篇原创文章 · 获赞 26 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_41211961/article/details/104255955