Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 265
Pete Avatar asked Feb 25 '11 12:02

Pete


3 Answers

You shall try this:

boost::split(line_parts, s_line, boost::is_any_of("\t,|"));
like image 100
Karl von Moor Avatar answered Nov 12 '22 16:11

Karl von Moor


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/`
}
like image 10
Lightness Races in Orbit Avatar answered Nov 12 '22 16:11

Lightness Races in Orbit


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.

like image 5
Matthieu M. Avatar answered Nov 12 '22 14:11

Matthieu M.