/*
键值对(”key = valude”)字符串,在开发中经常使用;
要求1:请自己定义一个接口,实现根据key获取valude;40分
要求2:编写测试用例。30分
要求3:键值对中间可能有n多空格,请去除空格30分
注意:键值对字符串格式可能如下:
“key1 = valude1”
“key2 = valude2
“key3 = valude3”
“key4 = valude4”
“key5 = “
“key6 =“
“key7 = “
*/
int trimSpace012(char *str, char *newstr) //除去空格得到字符串
{
char *p = str;
int ncount = 0;
int i, j = 0;
if (str==NULL||newstr==NULL)
{
printf("func str");
return -1;
}
i = 0;
j = strlen(p) - 1;
while (isspace(p[i]) && p[i] != '\0')
{
i++;
}
while (isspace(p[j]) && p[j] != '\0')
{
j--;
}
ncount = j - i + 1;
strncpy(newstr, str + i, ncount);
newstr[ncount] = '\0';
return 0;
}
//找到键值后面的字符串并打印
int getKeyByValude(char *keyvaluebuf, char *keybuf, char *valuebuf, int * valuebuflen) {
char *p = NULL;
int ret = 0;
if (keyvaluebuf == NULL || keybuf == NULL || valuebuf == NULL)
{
return -1;
}
//1.查找key是不是在沐川之中
p = keyvaluebuf; //初始化辅助指针变量
p=strstr(p, keybuf);
if (p == NULL)
{
return -1;
}
p = p + strlen(keybuf);
//2.看有没有=号
p = strstr(p, "=");
if(p==NULL)
{
return -1;
}
//让辅助指针变量 重新达到下一次检索的条件
p = p + strlen("=");
//3.再登号后面 除去空格
ret= trimSpace012(p, valuebuf);
if (ret != 0)
{
printf("func getKeyByValude() err:%d\n", ret);
return ret;
}
return ret;
}
int main()
{
int ret = 0;
char buf[1024];
int buflen = 0;
char *keyandvalue = "key2 = valude2 ";
char *key = "key2";
ret = getKeyByValude(keyandvalue, key, buf, &buflen);
if (ret != 0)
{
printf("func getKeyByValude() err:%d\n", ret);
return ret;
}
printf("buf:%s\n", buf);
//getKeyByValude(“key1 = valude1”, ” key1”, buf, &len);
system("pause");
return ret;
}