string -> wstring
std::wstring StringToWstring(const std::string& str)
{
std::wstring result;
int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), nullptr, 0);
TCHAR* buffer = new TCHAR[2*(len + 1)];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);
buffer[len] = '\0';
result.append(buffer);
delete[] buffer;
return result;
}
wstring -> string
bool UnicodeToUtf8(std::wstring& unicodeString, std::string& utf8String)
{
utf8String = "";
if (_wcsicmp(unicodeString.c_str(), L"") == 0)
{
return false;
}
DWORD utf8StringLen = WideCharToMultiByte(CP_ACP, NULL, unicodeString.c_str(), -1, NULL, 0, NULL, FALSE);
if (0 == utf8StringLen)
{
return false;
}
char* tempUtf8String = new char[utf8StringLen + 1];
memset(tempUtf8String, 0, sizeof(char) * (utf8StringLen + 1));
if (0 == WideCharToMultiByte(CP_ACP, NULL, unicodeString.c_str(), -1, tempUtf8String, utf8StringLen, NULL, FALSE))
{
delete[] tempUtf8String;
tempUtf8String = NULL;
return false;
}
utf8String = (std::string)tempUtf8String;
delete[] tempUtf8String;
tempUtf8String = NULL;
return true;
}
更改string编码为gbk格式
std::string UTF8ToGB(const char* str)
{
std::string result;
WCHAR* strSrc;
LPSTR szRes;
int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
strSrc = new WCHAR[i + 1];
MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);
i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
szRes = new CHAR[i + 1];
WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);
result = szRes;
delete[]strSrc;
delete[]szRes;
return result;
}
wchar_t* -> string
void Wchar_tToString(std::string& szDst, wchar_t* wchar)
{
wchar_t* wText = wchar;
DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, NULL, 0, NULL, FALSE);
char* psText;
psText = new char[dwNum];
WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, psText, dwNum, NULL, FALSE);
szDst = psText;
delete[]psText;
}