#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;
}