9

对你们来说应该是一件容易的事......

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

    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

更新

4

1 回答 1

15

您必须将分隔符提供给标记器!

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

此外,将已弃用的 char_delimiters_separator 替换为 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";
}

请注意,还有一个模板参数不匹配:对此类复杂类型进行 typedef 是一个好习惯:所以最终版本可能是:

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";
}
于 2011-10-29T21:12:05.880 回答