#include "stdlib.h"
#include "stdio.h"
#include "string.h"
// 求去掉空格后的字符串
int trimSpaceStr(char* ptr, char* out_buf) {
int ret = 0;
int count = 0;
int head, end;
head = 0;
end = strlen(ptr) - 1; // 注意:从0开始,所以要长度-1
//printf("ptr[end]:%c\n", ptr[end]);
//printf("strlen(ptr):%d, end:%d\n", strlen(ptr), end);
while (isspace(ptr[head]) && ptr[head] != '\0') {
head++;
}
while (isspace(ptr[end]) && end > 0) {
end--;
}
//if ( end > head) { // 避免char* ptr = " "; 字符串都是空格时,end - head为负数
// count = end - head + 1;
//}
count = end - head + 1;
strncpy(out_buf, ptr + head, count);
out_buf[count] = '\0';
return ret;
}
// 正确实例demo:
// C++工程项目,写代码思路逻辑清晰,让人看一眼能很快明白。
int getKeyByValue(char* pKeyValue, char* pKey, char* pValue) {
int rv = 0;
char* p = NULL;
char buf[1024] = {0}; // 用于局部变量在函数内调试
// 输入参数异常判断逻辑
//if (pKeyValue == NULL || pKey == NULL || pValue == NULL) {
// rv = -1;
// printf("func getKeyByValue() err:%d pKeyValue == NULL || pKey == NULL || pValue == NULL\n", rv);
// return rv;
//}
if (pKeyValue == NULL) {
rv = -1;
printf("func getKeyByValue() err:%d pKeyValue is NULL\n", rv);
return rv;
}
if (pKey == NULL) {
rv = -1;
printf("func getKeyByValue() err:%d pKey is NULL\n", rv);
return rv;
}
if (pValue == NULL) {
rv = -1;
printf("func getKeyByValue() err:%d pValue is NULL\n", rv);
return rv;
}
// 1,在pKeyValue中查找是否有关键字pKey
p = strstr(pKeyValue, pKey);
if (p == NULL) {
// pKeyValue字符串中未找到key
rv = -1;
printf("func getKeybyValue() err:%d 没有关键字pKey:%s\n", rv, pKey);
return rv;
}
p = p + strlen(pKey); // 为下次检索做准备
// 2,有没有=等号
p = strstr(p, "=");
if (p == NULL) {
// pKeyValue字符串中未找到=等号
rv = -2;
printf("func getKeybyValue() err:%d 没有=等号\n", rv);
return rv;
}
p = p + 1; // 为下一次提取value做准备
// 3,提取出value
//rv = trimSpaceStr(p, buf);
rv = trimSpaceStr(p, pValue);
if (rv != 0) {
printf("func trimSpaceStr err:%d\n", rv);
return rv;
}
return 0;
}
// 不推荐的写法-if,for深度嵌套逻辑:
// 工程项目上,会尽量避免if,for等等深度嵌套逻辑,这会让人看一眼还不明白逻辑。
int getKeyByValue01_Error(char* pKeyValue, char* pKey, char* pValue) {
char rv = 0;
char* p = NULL;
char buf[1024] = { 0 }; // 用于局部变量在函数内调试
// 1,在pKeyValue中查找是否有关键字pKey
p = strstr(pKeyValue, pKey);
if (p != NULL) {
p = p + strlen(pKey); // 为下次检索做准备
// 2,有没有=等号
p = strstr(p, "=");
if (p != NULL) {
p = p + 1; // 为下一次提取value做准备
// 3,提取出value
//rv = trimSpaceStr(p, buf);
rv = trimSpaceStr(p, pValue);
if (rv != 0) {
printf("func trimSpaceStr err:%d\n", rv);
return rv;
}
}
}
return 0;
}
void main() {
int ret = 0;
char KeyValue[] = "key1=value1";
char Key[] = "key1";
char Value[1024] = {0};
ret = getKeyByValue(KeyValue, Key, Value);
if (ret != 0) {
printf("func getKeyByValue() err:%d\n", ret);
}
printf("Value:%s\n", Value);
system("pause");
}
C语言键值对(key-value)操作练习
最新推荐文章于 2024-06-07 15:49:14 发布