如何使用C ++拆分带分隔符的字符串?

时间:2014-10-12 18:59:20

标签: c++ string

您好我有以下字符串

{
"data1" : "sample data",
"data2" : "sample data2"
}

我想使用字符串库将上面的字符串拆分为

data1
sample data

以下是我提出的代码,但它只是向左和向右分裂。上面的数据存储在缓冲区中并由line_number迭代。

if(pos != std::string::npos)
            {
                newpos = buffer[line_number].find_first_of(":",pos);
                token = buffer[line_number].substr(pos + 1,newpos-pos-1);
                pos = newpos + 1;
                std::cout << token << std::endl;
            }

非常感谢帮助。

1 个答案:

答案 0 :(得分:0)

非常简单的解析器可能如下所示:

#include <iostream>
#include <string>
#include <vector>
#include <map>

using namespace std;

static string& strip(string& s, const 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 string& s, vector<string>& tokens, const string& delimiters = " ")
{
        string::size_type lastPos = s.find_first_not_of(delimiters, 0);
        string::size_type pos = s.find_first_of(delimiters, lastPos);
        while (string::npos != pos || 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(string& s, map<string,string>& items)
{
        vector<string> elements;
        s.erase(0, s.find_first_not_of(" {"));
        s.erase(s.find_last_not_of("} ") + 1);
        split(s, elements, ",");
        for (vector<string>::iterator iter=elements.begin(); iter != elements.end(); iter++) {
                vector<string> kv;
                split(*iter, kv, ":");
                if (kv.size() != 2) continue;
                items[strip(kv[0], " \"")] = strip(kv[1], " \"");
        }
}

int
main()
{
        string data = "  {  \"key1\"  :  \"data1\"  ,  \"key2\"  :  \"data2\"    }  ";
        map<string,string> items;
        parse(data, items);

        for (map<string,string>::iterator iter=items.begin(); iter != items.end(); iter++) {
                cout << "key=" << (*iter).first << ",value=" << (*iter).second << endl;
        }
}