【问题标题】:Boost::tokenizer comma separated (c++)Boost::tokenizer 逗号分隔 (c++)
【发布时间】:2011-10-29 21:08:06
【问题描述】:

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

我正在使用 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

更新

【问题讨论】:

  • 与此问题类似:如果我在您的代码中修改了this is,,,a testcout &lt;&lt; "&lt;" &lt;&lt; *beg &lt;&lt; "&gt; ";,我如何也获得空字符串,如&lt;this is&gt; &lt;&gt; &lt;&gt; &lt;a string&gt;

标签: c++ boost tokenize boost-tokenizer


【解决方案1】:

你必须把分隔符给分词器!

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

【讨论】:

  • 另外,现在我的输出用逗号和空格分隔,我想忽略空格,我不想在输出中包含逗号(请参阅上面的更新问题)...
  • 而不是 typedefing 只是为了使用迭代器,你可以使用 auto
  • @Dani,实际上你不能。 auto 仅在 c++11 标准中有效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多