#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define nullptr NULL
// 去除首尾空格
int strRemoveSpace(char* distination, char* source)
{
if (distination == nullptr || source == nullptr)
{
return -1;
}
char* p1 = source;
char* p2 = source + strlen(source) - 1;
// 1、查找source字符串前置空格,找到就跳过,最终确定头指针位置(空格结束)
while (*p1 == ' ')
{
p1++;
}
// 2、按照上面的方法处理,最终确定尾指针的位置
while (*p2 == ' ')
{
p2--;
}
// 3、把值赋给 distination
while (p1 <= p2)
{
*distination = *p1;
distination++;
p1++;
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
// 做一个键值对读取的函数,根据key读取value
// key = "value"
//
int getKeybyValue(char* pKeyValude, char* pKey, char* pValude)
{
char rv = 0;
char* p = nullptr;
//char buf[1024];
//////////////////////////////////////////////////////////////////////////
// 这种写法不是太详细,如果环境复杂,应该采用下面那种写法
if (pKeyValude == nullptr || pKey == nullptr || pValude == nullptr)
{
rv = -1;
printf("func getKeybyValue() err:%d pKeyValude == nullptr || pKey == nullptr || pValude == nullptr", rv);
return rv;
}
//////////////////////////////////////////////////////////////////////////
// 在环境复杂的情况下,应该采用这种写法
if (pKeyValude == nullptr)
{
rv = -1;
printf("func getKeybyValue() err:%d pKeyValude == nullptr", rv);
return rv;
}
if (pKey == nullptr)
{
rv = -1;
printf("func getKeybyValue() err:%d pKey == nullptr ", rv);
return rv;
}
if (pValude == nullptr)
{
rv = -1;
printf("func getKeybyValue() err:%d pValude == nullptr", rv);
return rv;
}
// 1、在pKeyValude中查找是否有关键字pKey
p = strstr(pKeyValude, pKey);
if (p == nullptr)
{
rv = -1;
printf("func getKeybyValue() err:%d 查找关键字pKey出错", rv);
return rv;
}
p = p + strlen(pKey); // 为下一次检索做准备
// 2、有没有=
p = strstr(p, "=");
if (p == nullptr)
{
// 大字符串中没有=
rv = -1;
printf("func getKeybyValue() err:%d 查找关键字=出错", rv);
return rv;
}
// 为下一次提取valude做准备
p = p + 1; // p = p+strlen('=');
// 3、提取按照要求的valude
//rv = strRemoveSpace(buf, p);
rv = strRemoveSpace(pValude, p);
if (rv != 0)
{
printf("func strRemoveSpace() err:%d \n", rv);
return rv;
}
return 0;
}
int main()
{
int ret = 0;
//char pKeyValude[] = "key1=valude1";
//char pKeyValude[] = "key1=valude1 ";
char pKeyValude[] = "key1= valude1 ";
char pKey[] = "key1";
char pValude[1024] = { 0 };
ret = getKeybyValue(pKeyValude, pKey, pValude);
if (ret != 0)
{
printf("func getKeybyValue() err:%d \n", ret);
return ret;
}
printf("Valude:%s \n", pValude);
//system("pause");
return 0;
}