Lexicon
Lexicon

Reputation: 2627

Boost::tokenizer comma separated (c++)

Should be an easy one for you guys.....

I'm playing around with tokenizers using Boost and I want create a token that is comma separated. here is my code:

    string s = "this is, , ,  a test";
boost::char_delimiters_separator<char> sep(",");
boost::tokenizer<boost::char_delimiters_separator<char>>tok(s, sep);


for(boost::tokenizer<>::iterator beg= tok.begin(); beg!=tok.end(); ++beg)
{
    cout << *beg << "\n";
}

The output that I want is:

This is


 a test

What I am getting is:

This
is
,
,
,
a
test

UPDATED

Upvotes: 10

Views: 18377

Answers (2)

Riot
Riot

Reputation: 16696

With modern C++, a much simpler formulation is possible than the other answer provides:

std::string my_string = "this is, , ,  a test";

for(auto const &substring : boost::tokenizer{my_string, boost::char_separator{","}}) {
  std::cout << substring << std::endl;
}

Upvotes: 0

CapelliC
CapelliC

Reputation: 60004

You must give the separator to tokenizer!

boost::tokenizer<boost::char_delimiters_separator<char>>tok(s, sep);

Also, replace the deprecated char_delimiters_separator with char_separator:

string s = "this is, , ,  a test";
boost::char_separator<char> sep(",");
boost::tokenizer< boost::char_separator<char> > tok(s, sep);
for(boost::tokenizer< boost::char_separator<char> >::iterator beg = tok.begin(); beg != tok.end(); ++beg)
{
    cout << *beg << "\n";
}

Please note that there is also a template parameter mismatch: it's good habit to typedef such complex types: so the final version could be:

string s = "this is, , ,  a test";
boost::char_separator<char> sep(",");
typedef boost::tokenizer< boost::char_separator<char> > t_tokenizer;
t_tokenizer tok(s, sep);
for (t_tokenizer::iterator beg = tok.begin(); beg != tok.end(); ++beg)
{
    cout << *beg << "\n";
}

Upvotes: 16

Related Questions