Parse (split) a string in C++ using string delimiter (standard C++)

后端 未结 20 2547
时光说笑
时光说笑 2020-11-21 23:44

I am parsing a string in C++ using the following:

using namespace std;

string parsed,input=\"text to be parsed\";
stringstream input_stringstream(input);

i         


        
20条回答
  •  猫巷女王i
    2020-11-21 23:59

    I would use boost::tokenizer. Here's documentation explaining how to make an appropriate tokenizer function: http://www.boost.org/doc/libs/1_52_0/libs/tokenizer/tokenizerfunction.htm

    Here's one that works for your case.

    struct my_tokenizer_func
    {
        template
        bool operator()(It& next, It end, std::string & tok)
        {
            if (next == end)
                return false;
            char const * del = ">=";
            auto pos = std::search(next, end, del, del + 2);
            tok.assign(next, pos);
            next = pos;
            if (next != end)
                std::advance(next, 2);
            return true;
        }
    
        void reset() {}
    };
    
    int main()
    {
        std::string to_be_parsed = "1) one>=2) two>=3) three>=4) four";
        for (auto i : boost::tokenizer(to_be_parsed))
            std::cout << i << '\n';
    }
    

提交回复
热议问题