【问题标题】:using boost::split to split strings with multiple delimiters使用 boost::split 拆分具有多个分隔符的字符串
【发布时间】:2019-05-08 07:14:40
【问题描述】:

我有一个要拆分的字符串,所以我使用boost::split

但是boost::is_any_of 接受一个字符串并使用每个字符作为分隔符。

我的分隔符应该是“->”和“:”

":" 有效,因为它是单个字符分隔符,但 "->" 无效(它将每个字符("-" 和 ">" 分别作为分隔符)

std::vector<std::string> strs;
boost::split(strs, line, boost::is_any_of(["->:"]));

如何定义多个分隔符,其中一些分隔符不止一个字符?

例子:

"0:c->2"   should give [0,"c",2]

如果其他解决方案更容易解决特定问题,我愿意接受其他不使用 boost 的解决方案

【问题讨论】:

  • @VictorGubin 在标记器链接中我看到它们使用单​​字符分隔符,您能否提供一个如何使用“->”和“:”作为分隔符的示例?
  • @VictorGubin 此示例使用- ;| 作为分隔符。我不明白当你找到 -&gt; 时如何使用它们进行拆分,但当你单独找到 -&gt; 时却不能使用它们进行拆分

标签: c++ string boost


【解决方案1】:

你可以使用Boost.Spirit来解析字符串:

#include <string>
#include <vector>
#include <iostream>
#include <boost/spirit/include/qi.hpp>

namespace qi = boost::spirit::qi;

int main()
{
    std::string str = "0:c->2";
    std::vector< std::string > vec;

    auto it = str.begin(), end = str.end();
    bool res = qi::parse(it, end,
        qi::as_string[ *(qi::char_ - ':' - "->") ] % (qi::lit(':') | qi::lit("->")),
        vec);

    std::cout << "Parsed:";
    for (auto const& s : vec)
        std::cout << " \"" << s << "\"";

    std::cout << std::endl;
    return 0;
}

在这里,解析器生成与*(qi::char_ - ':' - "-&gt;") 解析器匹配的字符串列表(读作“任意数量的任何字符,除了':' 或“->””),由匹配@987654323 的字符串分隔@解析器(读作“':' 字符或“->”字符串”)。第一个解析器必须排除分隔符,否则它们将包含在解析的字符串中。 qi::as_string 部分只是将解析后的字符转换为 std::string 属性,然后将其附加到 vec 序列中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    相关资源
    最近更新 更多