【问题标题】:Multiple split tokens using boost::is_any_of使用 boost::is_any_of 的多个拆分令牌
【发布时间】:2011-07-04 06:48:53
【问题描述】:

我不确定如何使用boost::is_any_of 使用一组字符拆分字符串,其中任何一个字符都应该拆分字符串。

我想做这样的事情,因为我理解 is_any_of 函数需要一个 Set 参数。

std::string s_line = line = "Please, split|this    string";

std::set<std::string> delims;
delims.insert("\t");
delims.insert(",");
delims.insert("|");

std::vector<std::string> line_parts;
boost::split ( line_parts, s_line, boost::is_any_of(delims));

但是,这会产生一个 boost/STD 错误列表。 我应该坚持使用is_any_of 还是有更好的方法来做到这一点,例如。使用正则表达式拆分?

【问题讨论】:

  • 很遗憾is_any_of 没有使用迭代器范围。

标签: c++ string boost stl


【解决方案1】:

你应该试试这个:

boost::split(line_parts, s_line, boost::is_any_of("\t,|"));

【讨论】:

    【解决方案2】:

    如果没有名为 line 的预先存在的变量,您的第一行是无效的 C++ 语法,并且 boost::is_any_of 不采用 std::set 作为构造函数参数。

    #include <string>
    #include <set>
    #include <vector>
    #include <iterator>
    #include <iostream>
    #include <boost/algorithm/string.hpp>
    
    int main()
    {
        std::string s_line = "Please, split|this\tstring";
        std::string delims = "\t,|";
    
        std::vector<std::string> line_parts;
        boost::split(line_parts, s_line, boost::is_any_of(delims));
    
        std::copy(
            line_parts.begin(),
            line_parts.end(),
            std::ostream_iterator<std::string>(std::cout, "/")
        );
    
        // output: `Please/ split/this/string/`
    }
    

    【讨论】:

      【解决方案3】:

      主要问题是boost::is_any_ofstd::stringchar* 作为参数。不是std::set&lt;std::string&gt;

      您应该将delims 定义为std::string delims = "\t,|",然后它将起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-08
        • 1970-01-01
        • 1970-01-01
        • 2019-05-08
        • 1970-01-01
        • 2018-06-05
        • 2022-06-30
        • 1970-01-01
        相关资源
        最近更新 更多