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

Pet*_*ete 26 c++ string boost stl

我不确定如何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));
Run Code Online (Sandbox Code Playgroud)

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

Kar*_*oor 32

你应该试试这个:

boost::split(line_parts, s_line, boost::is_any_of("\t,|"));
Run Code Online (Sandbox Code Playgroud)


Lig*_*ica 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/`
}
Run Code Online (Sandbox Code Playgroud)


Mat*_* M. 5

主要问题是boost::is_any_of将 astd::string或 achar*作为参数。不是std::set<std::string>.

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