简体   繁体   中英

Multiple split tokens using boost::is_any_of

I am unsure how to use boost::is_any_of to split a string using a set of characters, any ONE of which should split the string.

I wanted to do something like this as I understood the is_any_of function takes a Set parameter.

std::string s_line = line = "Please, split|this    string";

std::set<std::string> delims;
delims.insert("\t");
delims.insert(",");
delims.insert("|");

std::vector<std::string> line_parts;
boost::split ( line_parts, s_line, boost::is_any_of(delims));

However this produces a list of boost/STD errors. Should I persist with is_any_of or is there a better way to do this eg. using a regex split?

你应该试试这个:

boost::split(line_parts, s_line, boost::is_any_of("\t,|"));

Your first line is not valid C++ syntax without a pre-existing variable named line , and boost::is_any_of does not take a std::set as a constructor parameter.

#include <string>
#include <set>
#include <vector>
#include <iterator>
#include <iostream>
#include <boost/algorithm/string.hpp>

int main()
{
    std::string s_line = "Please, split|this\tstring";
    std::string delims = "\t,|";

    std::vector<std::string> line_parts;
    boost::split(line_parts, s_line, boost::is_any_of(delims));

    std::copy(
        line_parts.begin(),
        line_parts.end(),
        std::ostream_iterator<std::string>(std::cout, "/")
    );

    // output: `Please/ split/this/string/`
}

The main issue is that boost::is_any_of takes a std::string or a char* as the parameter. Not a std::set<std::string> .

You should define delims as std::string delims = "\\t,|" and then it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM