使用boost :: is_any_of的多个拆分令牌

问题描述 投票:25回答:3

我不确定如何使用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还是有更好的方法来做到这一点,例如。使用正则表达式拆分?

c++ string boost stl
3个回答
30
投票

你应该试试这个:

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

9
投票

如果没有名为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/`
}

2
投票

主要问题是boost::is_any_ofstd::stringchar*为参数。不是std::set<std::string>

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

© www.soinside.com 2019 - 2024. All rights reserved.