2011-02-25 23 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,|",然後才能正常工作。