您的当前位置:首页正文

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

2024-04-25 来源:钮旅网
c语⾔实现名值对通过key查找value

需求、例如:

1、\" key1 = value1 \" 通过\"key1\"从该字符串中查找出\"value\去除前后空格2、\" key1 == value1 \" 、\" key1 = = value1 \" 双等于号不合法头⽂件:

#include#include#include

函数原型:

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 = \" key1 = kkkki\"; 4

5 char *key = \"key1\"; 6

7 char value[100] = {0}; 8

9 getValue(keyAndValue, key, value);10

11 printf(\"value = *%s*\\n\", value);12 system(\"pause\");13 }

因篇幅问题不能全部显示,请点此查看更多更全内容