c指针应用:键值对"key=value"字符串,在开发中经常使用

来源:互联网 发布:网络电视32寸多少钱 编辑:程序博客网 时间:2024/05/16 11:15

/*要求写一个函数实现如下功能
要求1:自己定义一个接口,实现根据key获取value
要求2:编写测试用例
要求3:键值对中间可能有多个空格,请清除空格
键值对可能如下
“key1= buf1 “;
“key2= buf2 “;
“key3= buf3 “;
“key4= buf4 “;
“key5= buf5 “;
*/

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<ctype.h>   int trimspace(char *str, char *newstr)//除去buff前后空格{    char *phead = str;    int i = 0;    int j = strlen(phead) - 1;    if (phead == NULL || newstr == NULL)    {        return -1;    }    while (isspace(phead[i])&& phead[i] != '\0')    {        i++;    }    while (isspace(phead[j]) && phead[j] != '\0')    {        j--;    }    int count = j - i + 1;    strncpy(newstr, phead + i, count);    newstr[count] = '\0';    return 1;}int getbuff(char *keybuff, char *key, char *buf){    char *p = keybuff;//指针初始化    //判断是否存在key    p = strstr(p, key);    if (p == NULL)    {        printf("There is no %s", key);        return -1;    }    //判断等号是否存在    p = strstr(p, "=");    if (p == NULL)    {        printf("There is no buff for %s", key);        return -1;    }    //除去key对应字符子串的前后空格    p = keybuff+ strlen(key) + strlen("=");    int ret=trimspace(p, buf);    if (ret != 1)    {        printf("delete sapace fail");        return -1;    }    return 1;}void main(){    char *str[] = { "key1=  buf1     " ,"key2=   buf2    ", "key3=    buf3   ",                    "key4=     buf4  " ,"key5=      buf5 " };//  char *keybuf = "key2=   buf2    ";//  char *key = "key2";    char key[5];    char buf[50] = { 0 };    int ret,i;    printf("Please input key(key1~key5:");    scanf("%s", key);//  for (i = 0; i < 5; i++)    switch (key[3])    {    case '1':i = 0; break;    case '2':i = 1; break;    case '3':i = 2; break;    case '4':i = 3; break;    case '5':i = 4; break;    }    //ret = getbuff(keybuf, key, buf);    ret = getbuff(str[i], key, buf);    if (ret != 1)    {        printf("funtion getbuff err\n");    }    else    {        printf("%s:%s\n", key, buf);    }}
0 0
原创粉丝点击