1.GBK转UTF-8(解码),这方法包含两部分:DecodeUtf8fromString函数和WString2String函数--windows环境
std::string WString2String(std::wstring &in)
{
int nLen = WideCharToMultiByte(CP_ACP, 0, in.c_str(), -1, NULL, 0, NULL, NULL);
if (nLen <= 0) return std::string("");
char* pszDst = new char[nLen];
if (NULL == pszDst) return std::string("");
WideCharToMultiByte(CP_ACP, 0, in.c_str(), -1, pszDst, nLen, NULL, NULL);
pszDst[nLen - 1] = 0;
std::string strTemp(pszDst);
delete[] pszDst;
return strTemp;
}
//解码
std::string DecodeUtf8fromString(std::string in)
{
int len = 0;
len = in.length();
int unicodeLen = ::MultiByteToWideChar(CP_UTF8, 0, in.c_str(), -1, NULL, 0);
wchar_t * pUnicode;
pUnicode = new wchar_t[unicodeLen + 1];
memset(pUnicode, 0, (unicodeLen + 1)*sizeof(wchar_t));
::MultiByteToWideChar(CP_UTF8, 0, in.c_str(), -1, (LPWSTR)pUnicode, unicodeLen);
std::wstring rt;
rt = (wchar_t*)pUnicode;
delete pUnicode;
return WString2String(rt);
}
2.转码 其他编码转UTF-8,此方法包含两部分:EncodeUtf8fromString和EncodeUtf8fromWstring函数--windows环境
std::string EncodeUtf8fromWstring(std::wstring in)
{
std::string s(in.length() * 3 + 1, ' ');
size_t len = ::WideCharToMultiByte(CP_UTF8, 0,
in.c_str(), in.length(),
&s[0], s.length(),
NULL, NULL);
s.resize(len);
return s;
}
//(gbk)字符串转utf8---转码
std::string EncodeUtf8fromString(std::string in)
{
std::wstring wszStr;
int nLength = MultiByteToWideChar(CP_ACP, 0, in.c_str(), -1, NULL, NULL);
wszStr.resize(nLength);
LPWSTR lpwszStr = new wchar_t[nLength];
MultiByteToWideChar(CP_ACP, 0, in.c_str(), -1, lpwszStr, nLength);
wszStr = lpwszStr;
delete[] lpwszStr;
return EncodeUtf8fromWstring(wszStr);
}