boost 常用替换和转换

#include <boost/algorithm/string.hpp>

 boost::replace_all(m_strFont, ":", "\\:");

大小写转换涉及到四个函数:to_upper()to_upper()以及xxx_copy的版本。基本用法如下:

    cout << to_upper_copy(string("hello world")) << endl;

Trimming

Trimming函数主要有trim()trim_left()trim_right()和他们的xxx_copy和xxx_if版本。用于去除字符串首位的空白字符:

 

Predicates函数主要有:starts_with() 、ends_with() 、contains() 、equals() 、lexicographical_compare() 、all()以及他们的ixxx版本。

Find algorithms

查找算法有好几种:find()、first()find_last()find_nth() 、find_head()find_tail()find_token()find_regex()。常见的用法如

 

replace_all() 、replace_first()、 replace_last() 

 

    string str1("hello abc-*-ABC-*-aBc goodbye");
    vector<string> SplitVec;
    split(SplitVec, str1, is_any_of("-*"),
token_compress_on);

需要注意的是这里的token_compress_on参数,它可以吧连续多个分隔符当一个,默认没有打开,当用的时候一般是要打开的。

 

Join函数则是和split相反,用于把多个字符串拼接起来。

    std::array<string, 3> k = {"hello", "world", "123"};
    cout << join(k, "-");        //
输出结果为: hello-world-123

具体查看http://www.cnblogs.com/TianFang/archive/2013/02/04/28

这么多string的操作函数感觉足够了。

 

万能类型转换

#include <boost/lexical_cast.hpp>  

try 

     {  

        int c = lexical_cast<int>("wrong number");  

   }  

    catch(bad_lexical_cast & e)  

   {  

      printf("%s/r/n", e.what());  

    }  

 

 utf-8 unicode  ansi转换


#include <boost/locale.hpp>
#include <boost/system/error_code.hpp>
#include <boost/system/system_error.hpp>

using namespace boost::locale::conv;
try
{
//UTF-8  GBK GB2312
string source = "中国";  

//ANSI 转换为 UTF-8
string s = boost::locale::conv::between(source, "UTF-8", "GB2312" );  
std::cout << utf8_2_s(s) <<std::endl;

std::string strTmp = "中国";

//ANSI 转换为 UTF-8
std::string utf8_string = to_utf<char>(strTmp,"GB2312");
std::cout << utf8_2_s(utf8_string) <<std::endl;

//ANSI 转换为 unicode
std::wstring wide_string = to_utf<wchar_t>(strTmp,"GB2312");
std::cout << ws2s(wide_string) <<std::endl;
//unicode 转换为ansi
std::string latin1_string = from_utf(wide_string,"GB2312");

//unicode 转换为utf-8
std::string utf8_string2 = utf_to_utf<char>(wide_string);
std::cout << utf8_2_s(utf8_string2) <<std::endl;

// utf-8转换为unicode

std::wstring unicode_string3 = utf_to_utf<wchar_t>(utf8_string2);
std::cout << ws2s(unicode_string3) <<std::endl;
}
catch(const conversion_error& ec)
{
std::cout << ec.what() << std::endl;
}
catch (boost::system::error_code& ec)
{
std::cout << ec.message() << std::endl;
}
catch(boost::system::system_error &ec)
{
std::cout << ec.what() << std::endl;
}
catch(std::exception& ec)
{
std::cout << ec.what() << std::endl;

}
catch(...)
{
std::cout << "aaaa" << std::endl;
}


 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值