【字符串】面试题之键值对(”key = valude”)字符串
题目:
键值对(”key = valude”)字符串,在开发中经常使用;
要求1:请自己定义一个接口,实现根据key获取valude;40分
要求2:编写测试用例。30分
要求3:键值对中间可能有n多空格,请去除空格30分
注意:键值对字符串格式可能如下:
“key1 = value1”
“key2 = value2“
“key3 = value3”
“key4 = value4”
“key5 = value5“
“key6 =value6“
“key7 = value7“
//头文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
include <assert.h>//处理函数
//处理函数
int getKeyByValude(char keyvaluebuf, char *keybuf, char *valuebuf, int valuebuflen)
{
int i=0,j=0;//循环变量
char *p;//指向第一个字符
int count=0;//value的长度
int len=0;
assert(keyvaluebuf!=NULL);
p=strstr(keyvaluebuf,keybuf);//找到key
if (p==NULL)
{
return 0;
}
p=strchr(p,’=’);
p=p+1;//指针p指向“=”后面的字符
len=strlen(p);
j=i+len-1;
while (isspace(p[i])&&p[i]!=’\0’)
{
i++;
}
while (isspace(p[j])&&j>0)//p指向value的尾字符
{
j–;
}
count=j-i+1;
memcpy(valuebuf,p+i,count);
valuebuf[count]=’\0’;
*valuebuflen=count;
return 1;
}
//测试
int main()
{
char buf1[20];
char buf2[20];
char buf3[20];
int len1,len2,len3;
char *p1=”key1 = valuddsddsde1 “;
char *p2=”key2 = valu8”;
char *p3=”key3 = valud 9dsde1 “;
if(getKeyByValude(p1, “key1”, buf1, &len1))
{
printf(“原字符串:%s,目标字符串:%s, 长度:%d\n”,p1,buf1,len1);
}
if (getKeyByValude(p2, “key2”, buf2, &len2))
{
printf(“原字符串:%s,目标字符串:%s, 长度:%d\n”,p2,buf2,len2);
}
if (getKeyByValude(p3, “key3”, buf3, &len3))
{
printf(“原字符串:%s,目标字符串:%s, 长度:%d\n”,p3,buf3,len3);
}
return 0;
}