【问题标题】:boost::algorithm - splitting a string returns an extra tokenboost::algorithm - 拆分字符串会返回一个额外的标记
【发布时间】:2012-09-27 01:49:55
【问题描述】:

也许有人可以告诉我这里发生了什么?

我的意图是在大括号上拆分输入字符串:即:'(' 或 ')'。

对于 "(well)hello(there)world" 的输入字符串,我希望返回 4 个标记:well;你好;那里;世界

从下面的示例应用程序中可以看出,我得到了 5 个令牌(第一个是空字符串)。

有没有办法让这个只返回非空字符串?

#include <iostream>
#include <boost/algorithm/string.hpp>
#include <vector>
int main()
{
    std::string in = "(well)hello(there)world";

    std::vector<std::string> tokens;
    boost::split(tokens, in, boost::is_any_of("()"));

    for (auto s : tokens)
        std::cout << "\"" << s << "\"" << std::endl;

    return 0;
}

输出:

$ a.out
""        <-- where is this token coming from?
"well"
"hello"
"there"
"world"

我尝试过使用boost::algorithm::token_compress_on,但得到了相同的结果。

【问题讨论】:

  • 只是好奇,尝试删除well 之前的(。在第一个 ( 之前,空字符串可能没有任何意义。

标签: c++ string boost


【解决方案1】:

是的,返回的第一个结果是第一个左括号之前的空集 {}。行为符合预期。

如果您不想使用该结果,只需测试返回的空变量并将其丢弃。

要测试这是预期的行为,请在行尾放置一个括号,最后会得到另一个空结果。 :)

【讨论】:

  • 有趣的是我已经这样做了。我希望有类似skip_empty_tokens 参数之类的东西。我相信boost::tokenizer 可能有这个功能。
【解决方案2】:

这个线程有点旧,但这是更好的解决方案boost::token_compress_on,在boost::split 的分隔符之后添加这个

【讨论】:

  • 不,boost::token_compress_on 只会合并相邻的空标记,但它仍然会在字符串的开头生成一个空标记。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-22
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多