【C++】string通过key获取值

string StringTest::core_get_param_by_key(string data, string key)
{
int pos = 0;
int count = 0;
string str_sub = "";
string str_result = "";
string str_split = "\"";

// format: "key":"value","key2"...

// 方式1

key = key + "\":\"";
printf("***********key=%s\n", key.c_str());
pos = data.find(key);
if (pos == string::npos) {
return str_result;
}
str_sub = data.substr(pos + key.length(), data.length());
printf("***********str_sub=%s\n", str_sub.c_str());
pos = str_sub.find(str_split);
str_result = str_sub.substr(0, pos);
printf("***********pos=%d, str_result=%s\n", pos, str_result.c_str());
#if 0

//方式2
pos = data.find(key);
if (pos == string::npos) {
return str_result;
}
str_sub = data.substr(pos + key., data.length());
int size = str_sub.size();
pos = str_sub.find(str_split);
while (pos != string::npos) {
str_result = str_sub.substr(0, pos);
str_sub = str_sub.substr(pos + 1, size);
pos = str_sub.find(str_split);
size = str_sub.length();
count++;
if (count >= 3) {
break;
}
}
#endif
return str_result;
}

posted @ 2021-10-26 16:17  我自逍遥笑  阅读(323)  评论(0编辑  收藏  举报