2011-02-25 125 views
22

我不确定如何使用boost::is_any_of使用一组字符拆分字符串,其中任何一个字符都应拆分字符串。使用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还是有更好的方法来做到这一点,例如。使用正则表达式分割?

+0

“is_any_of”没有采用迭代器范围是一件很遗憾的事情。 – Inverse 2011-02-25 17:45:52

回答

27

您应该试试这个:

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/` 
} 
1

的许多问题是boost::is_any_of需要std::stringchar*作为参数。不是std::set<std::string>

您应该将delims定义为std::string delims = "\t,|",然后才能正常工作。