lexical_cast 字面量转换:
#include <iostream> #include <boost/lexical_cast.hpp> #include <string> int main() { int i = 0; try{ i = boost::lexical_cast<int>("100L"); //可能会抛出 bad_lexical_cast 异常 }catch(boost::bad_lexical_cast& e) { std::cout<<e.what()<<std::endl; } std::string s = boost::lexical_cast<std::string>(32.2); std::cout<<i<<"\n"<<s<<std::endl; //100 32.200000000000003 }
boost::format 字符串格式化:
#include <iostream> #include <string> #include <boost/format.hpp> int main() { std::cout<<boost::format("%s->%s = %d")%"user_ptr"%"userid"%20<<std::endl; //user_ptr->userid = 20 boost::format fmt("%1%,%2%,%2%,%3%"); fmt %1%2; fmt %3; std::cout<<fmt.str()<<std::endl; //1,2,2,3 }
#include <boost/algorithm/string.hpp>
int main() { std::string str = "Hello World!"; std::string str2 = "hello world!"; if(boost::ends_with(str,"!") && boost::istarts_with(str,"h")) { std::cout<<boost::to_upper_copy(str)<<"\n" <<boost::to_lower_copy(str)<<"\n" <<boost::replace_first_copy(str," ","--")<<"\n" <<boost::erase_first_copy(str," ")<<"\n" <<boost::iequals(str,str2)<<"\n" //带前缀i不区分大小写 <<boost::is_less()(str,str2)<<"\n" <<boost::icontains(str,"WO")<<"\n" <<boost::all(str2.substr(0,5),boost::is_lower())<<"\n" <<std::endl; } std::string str3 = " wo0000"; std::cout<<boost::trim_left_copy(str3)<<std::endl; std::cout<<boost::trim_copy_if(str3,boost::is_digit() || boost::is_space())<<std::endl; std::cout<<boost::find_first(str,"e")<<std::endl; //以上方法中有后缀 _copy的,表示返回字符串副本,原字符串未改变。 //可以不带后缀 _copy ,表示改变原字符串,但不返回该字符串。 //类似的还有加前缀 i 的方法,表示不区分大小写。 //后缀 _if 的方法表示需要一个作用判断式的谓语函数对象,否则使用默认判断准则 //all 检测一个字符串里所有的元素,是否满足指定的判断式。可惜没有加后缀_if //为配合all方法,提供了一组分类函数: //is_space, is_alnum, is_alpha, is_cntrl, is_digit, is_graph, is_lower, is_print, is_punct, is_upper, is_xdigit, is_any_of, if_from_range std::vector<std::string> vect; std::string str4 = "Hello World!Haha."; boost::split(vect,str4,boost::is_any_of(" !")); for(int i = 0; i < vect.size(); i++) { std::cout<<vect[i]<<std::endl; } std::vector<std::string> v = boost::assign::list_of("aa")("bb")("cc"); std::cout<<boost::join(v,"+")<<std::endl; }