1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| #include <iostream> #include <map> #include <string> #include <vector>
static std::string& strip(std::string& s, const std::string& chars = " ") { s.erase(0, s.find_first_not_of(chars.c_str())); s.erase(s.find_last_not_of(chars.c_str()) + 1); return s; }
static void split(const std::string& s, std::vector<std::string>& tokens, const std::string& delimiters = " ") { std::string::size_type lastPos = s.find_first_not_of(delimiters, 0); std::string::size_type pos = s.find_first_of(delimiters, lastPos); while (std::string::npos != pos || std::string::npos != lastPos) { tokens.push_back(s.substr(lastPos, pos - lastPos)); lastPos = s.find_first_not_of(delimiters, pos); pos = s.find_first_of(delimiters, lastPos); } }
static void parse(std::string& s, std::map<std::string, std::string>& items) { std::vector<std::string> elements; s.erase(0, s.find_first_not_of(" {")); s.erase(s.find_last_not_of("} ") + 1); split(s, elements, ","); for (auto& iter : elements) { std::vector<std::string> kv; split(iter, kv, ":"); if (kv.size() != 2) continue; items[strip(kv[0], " \"")] = strip(kv[1], " \""); } }
int main() { std::string data = " { \"key1\" : \"data1\" , \"key2\" : \"data2\" } "; std::map<std::string, std::string> items; parse(data, items);
for (const auto& iter:items){ std::cout << "key=" << iter.first << ",value=" << iter.second << std::endl; } system("pause"); }
|