2013-02-06 156 views
2

我正在尝试使用boost::is_any_ofboost::replace_all_copy来编写一段简单的代码。这段代码如下:如何使用boost :: is_any_of with boost :: replace_all_copy

std::string someString = "abc.def-ghi"; 
std::string toReplace = ".-"; 
std::string processedString = boost::replace_all_copy(someString, boost::is_any_of(toReplace), " "); 

但是,我得到一个编译器错误太长,无法粘贴到这里。有人有这两种功能的经验,请指出我的错误?

回答

2

我不太熟悉那个特定的方法,但看起来replace_all_copy只想要一个替换字符串而不是is_any_of的结果。

通过对string algorithms我注意到,有一个正则表达式版本,也将工作中的其他选项扫视:

#include <iostream>                                         
#include <boost/algorithm/string.hpp>                                     
#include <boost/algorithm/string/regex.hpp>                                   

int main(int argc, char** argv) {                                      
    std::string someString = "abc.def-ghi";                                   
    std::cout << someString << std::endl;                                    
    std::string toReplace = "[.-]"; // character class that matches . and -                           
    std::string replacement = " ";                                     
    std::string processedString =                                      
     boost::replace_all_regex_copy(someString, boost::regex(toReplace), replacement);                        
    std::cout << processedString << std::endl;                                  
    return 0;                                           
} 

输出:

abc.def-ghi 
abc def ghi 

这确实需要链接到的升压正则表达式库。就我而言,我建:

g++ -L/usr/local/Cellar/boost/1.52.0/lib -lboost_regex-mt main.cpp

6

我不认为你不能。 The three parameter version of boost::replace_all_copy接受输入字符串,替代字符串和字符串进行搜索。 boost::is_any_of返回的是谓词仿函数。

你可能想要的是boost::replace_if

#include <boost/algorithm/string.hpp>   // for is_any_of 
#include <boost/range/algorithm/replace_if.hpp> // for replace_if 
#include <string> 
#include <iostream> 

std::string someString = "abc.def-ghi"; 
std::string toReplace = ".-"; 
std::string processedString = 
    boost::replace_if(someString, boost::is_any_of(toReplace), ' '); 

int main() 
{ 
    std::cout << processedString; 
} 

此修改原始,所以如果你需要保留它,你可以使用boost::replace_copy_if

#include <boost/algorithm/string.hpp> 
#include <boost/range/algorithm/replace_copy_if.hpp> 
#include <string> 
#include <iostream> 
#include <iterator> // for back_inserter 

std::string someString = "abc.def-ghi"; 
std::string toReplace = ".-"; 

int main() 
{ 
    std::string processedString; 
    boost::replace_copy_if(someString, 
     std::back_inserter(processedString), boost::is_any_of(toReplace), ' '); 
    std::cout << processedString; 
} 

希望有所帮助。

+0

我也在看,以及我不确定复制部分对于原始问题的重要性。基于文档,它看起来像someString将被修改,并返回一个引用。如果复制不重要,我更喜欢你的解决方案,因为你避免使用正则表达式。 –

+0

@JesseVogt好点,我更新了答案。 – jrok

+0

酷 - 不知道我完全错过了看文档中的replace_copy_if。好的解决方案 –