C++常用字符集转换方法一

  • Post author:
  • Post category:其他


C++常用字符转换UTF8到string类型:

直接使用boost库中函数,在编译的时候要

链接libboost_locale.so 库

;此方法可以直接跨平台使用,在linux、window下都适用

例如:在代码中这接写中文转UTF8码,可以使用如下接口

string str=“中国”

string utf8Str = GB2312toUTF8(str);

#include <boost/locale.hpp>
#include <string>
#include <boost/locale/encoding.hpp>

std::string UTF8toGBK(const std::string& str);

std::string GBKtoUTF8(const std::string& str);

std::string UTF8toGB2312(const std::string& str);

std::string GB2312toUTF8(const std::string& str);

std::wstring GBKtoUNICODE(const std::string& str);

std::string UNICODEtoGBK(std::wstring wstr);

std::string UNICODEtoUTF8(const std::wstring& wstr);

std::wstring UTF8toUNICODE(const std::string& str);
std::string UTF8toGBK(const std::string& str)
{
	return boost::locale::conv::between(str, "GBK", "UTF-8");
}

std::string GBKtoUTF8(const std::string& str)
{
	return boost::locale::conv::between(str, "UTF-8", "GBK");
}

std::string UTF8toGB2312(const std::string& str)
{
	return boost::locale::conv::between(str, "GBK", "GB2312");
}

std::string GB2312toUTF8(const std::string& str)
{
	return boost::locale::conv::between(str, "UTF-8", "GB2312");
}

std::wstring GBKtoUNICODE(const std::string& str)
{
	return boost::locale::conv::to_utf<wchar_t>(str, "GBK");
}

std::string UNICODEtoGBK(std::wstring wstr)
{
	return boost::locale::conv::from_utf(wstr, "GBK");
}

std::string UNICODEtoUTF8(const std::wstring& wstr)
{
	return boost::locale::conv::from_utf(wstr, "UTF-8");
}

std::wstring UTF8toUNICODE(const std::string& str)
{
	return boost::locale::conv::utf_to_utf<wchar_t>(str);
}



版权声明:本文为fengyunzhenyu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。