boost::algorithm - 拆分字符串会返回一个额外的标记

boost::algorithm - splitting a string returns an extra token

本文关键字:一个 拆分 algorithm 字符串 boost 返回      更新时间:2023-10-16

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

我的目的是在大括号上拆分输入字符串:即:"("或""。

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

正如您从下面的示例应用程序中看到的那样,我得到了 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但我得到相同的结果。

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

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

若要测试这是预期行为,请在行尾加上一个括号,最后将得到另一个空结果。 :)

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