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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5117201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:26:02  来源:igfitidea点击:

Multiple split tokens using boost::is_any_of

c++stringbooststl

提问by Pete

I am unsure how to use boost::is_any_ofto split a string using a set of characters, any ONE of which should split the string.

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

I wanted to do something like this as I understood the is_any_of function takes a Set parameter.

我想做这样的事情,因为我理解 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));

However this produces a list of boost/STD errors. Should I persist with is_any_ofor is there a better way to do this eg. using a regex split?

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

回答by Karl von Moor

You shall try this:

你应该试试这个:

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

回答by Lightness Races in Orbit

Your first line is not valid C++ syntax without a pre-existing variable named line, and boost::is_any_ofdoes not take a std::setas a constructor parameter.

如果没有名为 的预先存在的变量line,您的第一行不是有效的 C++ 语法,并且boost::is_any_of不将 astd::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/`
}

回答by Matthieu M.

The main issue is that boost::is_any_oftakes a std::stringor a char*as the parameter. Not a std::set<std::string>.

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

You should define delimsas std::string delims = "\t,|"and then it will work.

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