需求、例如:
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 = " 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 }
