Boost :: tokenizer逗号分隔(c ++)

时间:2011-10-29 21:08:06

标签: c++ boost tokenize boost-tokenizer

对你们来说应该很容易......

我正在玩使用Boost的tokenizer,我想创建一个以逗号分隔的标记。这是我的代码:

    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";
}

我想要的输出是:

This is


 a test

我得到的是:

This
is
,
,
,
a
test

已更新

1 个答案:

答案 0 :(得分:14)

您必须将分隔符分配给tokenizer!

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

另外,用char_separator替换已弃用的char_delimiters_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";
}

请注意,还有一个模板参数不匹配:输入这样复杂类型的好习惯:所以最终版本可能是:

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";
}
相关问题