1.UTF8(string)转 wstring(这里的wstring就是unicode也就是utf16)
std::wstring UTF82Wide(const std::string& strUTF8)
{
int nWide = ::MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), strUTF8.size(), NULL, 0);
std::unique_ptr<wchar_t[]> buffer(new wchar_t[nWide + 1]);
if (!buffer)
{
return L"";
}
::MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), strUTF8.size(), buffer.get(), nWide);
buffer[nWide] = L'\0';
return buffer.get();
}
2.wstring 转 UTF8(string)
std::string Wide2UTF8(const std::wstring& strWide)
{
int nUTF8 = ::WideCharToMultiByte(CP_UTF8, 0, strWide.c_str(), strWide.size(), NULL, 0, NULL, NULL);
std::unique_ptr<char[]> buffer(new char[nUTF8 + 1]);
if (!buffer)
{
return "";
}
::WideCharToMultiByte(CP_UTF8, 0, strWide.c_str(), strWide.size(), buffer.get(), nUTF8, NULL, NULL);
buffer[nUTF8] = '\0';
return buffer.get();
}
3.ANSI(GBK)转 wstring
std::wstring Ansi2Wide(const std::string& strAnsi)
{
int nWide = ::MultiByteToWideChar(CP_ACP, 0, strAnsi.c_str(), strAnsi.size(), NULL, 0);
std::unique_ptr<wchar_t[]> buffer(new wchar_t[nWide + 1]);
if (!buffer)
{
return L"";
}
::MultiByteToWideChar(CP_ACP, 0, strAnsi.c_str(), strAnsi.size(), buffer.get(), nWide);
buffer[nWide] = L'\0';
return buffer.get();
}
4.wstring 转 ANSI
std::string Wide2Ansi(const std::wstring& strWide)
{
int nAnsi = ::WideCharToMultiByte(CP_ACP, 0, strWide.c_str(), strWide.size(), NULL, 0, NULL, NULL);
std::unique_ptr<char[]> buffer(new char[nAnsi + 1]);
if (!buffer)
{
return "";
}
::WideCharToMultiByte(CP_ACP, 0, strWide.c_str(), strWide.size(), buffer.get(), nAnsi, NULL, NULL);
buffer[nAnsi] = '\0';
return buffer.get();
}
5。utf16转utf8
string StrUtil::Utf16ToUtf8(const wstring& str)
{
//含\0
int len = ::WideCharToMultiByt