#include <stdio.h>#include <stdlib.h>#include <string.h>#define nullptr NULL// 去除首尾空格int strRemoveSpace(char* distination, char* source){ if (distination == nullptr || source == nullptr) { return -1; } char* p1 = source; char* p2 = source + strlen(source) - 1; // 一、查找source字符串前置空格,找到就跳過,最終肯定頭指針位置(空格結束) while (*p1 == ' ') { p1++; } // 二、按照上面的方法處理,最終肯定尾指針的位置 while (*p2 == ' ') { p2--; } // 三、把值賦給 distination while (p1 <= p2) { *distination = *p1; distination++; p1++; } return 0;}//////////////////////////////////////////////////////////////////////////// 作一個鍵值對讀取的函數,根據key讀取value// key = "value"//int getKeybyValue(char* pKeyValude, char* pKey, char* pValude){ char rv = 0; char* p = nullptr; //char buf[1024]; ////////////////////////////////////////////////////////////////////////// // 這種寫法不是太詳細,若是環境複雜,應該採用下面那種寫法 if (pKeyValude == nullptr || pKey == nullptr || pValude == nullptr) { rv = -1; printf("func getKeybyValue() err:%d pKeyValude == nullptr || pKey == nullptr || pValude == nullptr", rv); return rv; } ////////////////////////////////////////////////////////////////////////// // 在環境複雜的狀況下,應該採用這種寫法 if (pKeyValude == nullptr) { rv = -1; printf("func getKeybyValue() err:%d pKeyValude == nullptr", rv); return rv; } if (pKey == nullptr) { rv = -1; printf("func getKeybyValue() err:%d pKey == nullptr ", rv); return rv; } if (pValude == nullptr) { rv = -1; printf("func getKeybyValue() err:%d pValude == nullptr", rv); return rv; } // 一、在pKeyValude中查找是否有關鍵字pKey p = strstr(pKeyValude, pKey); if (p == nullptr) { rv = -1; printf("func getKeybyValue() err:%d 查找關鍵字pKey出錯", rv); return rv; } p = p + strlen(pKey); // 爲下一次檢索作準備 // 二、有沒有= p = strstr(p, "="); if (p == nullptr) { // 大字符串中沒有= rv = -1; printf("func getKeybyValue() err:%d 查找關鍵字=出錯", rv); return rv; } // 爲下一次提取valude作準備 p = p + 1; // p = p+strlen('='); // 三、提取按照要求的valude //rv = strRemoveSpace(buf, p); rv = strRemoveSpace(pValude, p); if (rv != 0) { printf("func strRemoveSpace() err:%d \n", rv); return rv; } return 0;}int main(){ int ret = 0; //char pKeyValude[] = "key1=valude1"; //char pKeyValude[] = "key1=valude1 "; char pKeyValude[] = "key1= valude1 "; char pKey[] = "key1"; char pValude[1024] = { 0 }; ret = getKeybyValue(pKeyValude, pKey, pValude); if (ret != 0) { printf("func getKeybyValue() err:%d \n", ret); return ret; } printf("Valude:%s \n", pValude); //system("pause"); return 0;}