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

/*要求写一个函数实现如下功能
要求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);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值