用到的主要函數是WideCharToMultiByte,在這個函數中主要的是第一個參數,這個參數的具體說明參照msdn。下面給幾個字符串轉化的例子:
1、將LPCWSTR轉化成string類型
BOOL WCharToMByte(LPCWSTR lpcwszStr, string &str)
{
DWORD dwMinSize = 0;
LPSTR lpszStr = NULL;
dwMinSize = WideCharToMultiByte(CP_ACP, NULL, lpcwszStr, -1, NULL, 0, NULL, FALSE);
if (0 == dwMinSize)
{
return FALSE;
}
lpszStr = new char[dwMinSize];
WideCharToMultiByte(CP_ACP, NULL, lpcwszStr, -1, lpszStr, dwMinSize, NULL, FALSE);
str = lpszStr;
delete[] lpszStr;
return TRUE;
}
這個函數的作用是將TCHAR類型的字符串轉化成ANSI類型的字符串。
2、將ANSI類型的字符串轉化成UTF16編碼形式的字符串
std::wstring ANSI_2_UTF16(const string& strANSI)
{
int nUnicodeLength = ::MultiByteToWideChar(CP_ACP, 0, strANSI.c_str(), -1, NULL, 0);
wstring strUTF16(nUnicodeLength, _T(' '));
int nRet = ::MultiByteToWideChar(CP_ACP, 0, strANSI.c_str(), -1, &strUTF16[0], nUnicodeLength);
ASSERT(0 != nRet);
return strUTF16;
}
這個函數就是將1中轉化成的ANSI的字符串轉化成UTF16編碼形式的字符串。
3、將ANSI字符串轉化成UTF8編碼形式的字符串
char* char_2_UTF8(char* str)
{
int nLen = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0);
if (nLen == 0)
return "";
WCHAR *pwszBuffer = new WCHAR[nLen];
nLen = MultiByteToWideChar(CP_ACP, 0, str, -1, pwszBuffer, nLen);
if (nLen == 0)
return "";
nLen = WideCharToMultiByte(CP_UTF8, 0, pwszBuffer, -1, NULL, 0, NULL, NULL);
if (nLen == 0)
return "";
char *pszBuffer = new char[nLen];
nLen = WideCharToMultiByte(CP_UTF8, 0, pwszBuffer, -1, pszBuffer, nLen, NULL, NULL);
if (nLen == 0)
return "";
nLen = strlen(pszBuffer) + 1;
NPUTF8 * strUTF8 = static_cast<NPUTF8 *>(NPN_MemAlloc(nLen));
memset(strUTF8, 0, nLen);
strncpy(strUTF8, pszBuffer, nLen);
return strUTF8;
}
4、將string轉化成WCHAR類型字符串
std::wstring s2ws(const std::string& s)
{
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}