0%

C++字符串分割与解析代码学习

源码链接

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>

/**
* @brief 把字符串前后的字符串给去除
* @param s [in] 要剪切的字符串
* @param chars [in] 要去除什么的字符串
* @return std::string& 剪切后的字符串
* @author lijiancong(lijiancong@gbcom.com.cn)
* @note
*/
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;
}

/**
* @brief 以特定符号为分隔符,切分字符串并放入vector里
* @param s [in] 原字符串
* @param tokens [out] 剪切后的子字符串
* @param delimiters [in] 分隔符
* @author lijiancong(lijiancong@gbcom.com.cn)
* @note
*/
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");
}