首页 > 代码库 > c语言实现名值对通过key查找value

c语言实现名值对通过key查找value

需求、例如:

1、" key1 = value1 " 通过"key1"从该字符串中查找出"value",value去除前后空格

2、" key1 == value1 " 、" key1 = = value1 " 双等于号不合法

头文件:

#include<stdlib.h>
#include<stdio.h>
#include<string.h>

 

函数原型:

void trim(char *strIn /*in*/, char *strOut /*out*/);

void getValue(char * keyAndValue  /*in*/, char * key  /*in*/, char * value /*out*/);

实现方法:

 1 void trim(char *strIn, char *strOut){
 2 
 3     char *start, *end, *temp;//定义去除空格后字符串的头尾指针和遍历指针
 4 
 5     temp = strIn;
 6 
 7     while (*temp ==  ){
 8         ++temp;
 9     }
10 
11     start = temp; //求得头指针
12 
13     temp = strIn + strlen(strIn) - 1; //得到原字符串最后一个字符的指针(不是‘\0‘)
14 
15     while (*temp ==  ){
16         --temp;
17     }
18 
19     end = temp; //求得尾指针
20 
21 
22     for(strIn = start; strIn <= end; ){
23         *strOut++ = *strIn++;
24     }
25 
26     *strOut = \0;
27 }
 1 void getValue(char * keyAndValue, char * key, char * value){
 2 
 3     char *p = keyAndValue;
 4 
 5     p = strstr(keyAndValue, key);
 6     if(p == NULL){
 7         printf("没有key\n");
 8         return ;
 9     }
10 
11     p += strlen(key);
12     trim(p, value);
13 
14     p = strstr(value, "=");
15     if(p == NULL){
16         printf("没有=\n");
17         return;
18     }
19     p+= strlen("=");
20     trim(p, value);
21 
22     p = strstr(value, "=");
23     if(p != NULL){
24         printf("多余的=\n");
25         return;
26     }
27     p = value;
28     trim(p, value);
29 
30 }

测试:

 1 void main(){
 2 
 3     char *keyAndValue = http://www.mamicode.com/" key1 = kkkki";
 4     
 5     char *key = "key1";
 6 
 7     char value[100] = {0};
 8 
 9     getValue(keyAndValue, key, value);
10 
11     printf("value = http://www.mamicode.com/*%s*/n", value);
12     system("pause");
13 }

 

c语言实现名值对通过key查找value