解析形如(k,v)(k,v)(k,v)字符串

有时根据需要会将map数据格式化成(k,v)(k,v)(k,v)……字符串,之后需要还原,下面代码实现了还原过程

 1 void SplitString(const string& s, vector<string>& v, const string& c)
 2 {
 3     string::size_type pos1, pos2;
 4     pos2 = s.find(c);
 5     pos1 = 0;
 6     while(string::npos != pos2)
 7     {
 8         v.push_back(s.substr(pos1, pos2-pos1));
 9 
10         pos1 = pos2 + c.size();
11         pos2 = s.find(c, pos1);
12     }
13     if(pos1 != s.length())
14         v.push_back(s.substr(pos1));
15 }
16 
17 //格式是:(k,v)(k,v)(k,v)
18 void ParseAttribute(string strAttr, map<string,string>& attr)
19 {
20     if (strAttr.empty())
21     {
22         return ;
23     }
24     vector<string> v;
25     SplitString(strAttr, v, ")");
26     for (int i = 0; i < v.size(); ++i)
27     {
28         string str = v[i];
29         str.erase(str.begin(), str.begin() + str.find('(') + 1);
30         vector<string> v1;
31         SplitString(str, v1, ",");
32         if ((v1.size() != 2) || (v1[0].empty()))
33         {
34             continue;
35         }
36 
37         attr.insert(make_pair(v1[0], v1[1]));
38     }
39 }
作者:快雪
本文版权归作者所有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/kuaixue/p/12727889.html