在平時的編程中字符串轉換經常遇到,常用的是MultiByteToWideChar和WideCharToMultiByte,具體的函數如下:
/////////////////////////////////////////////////////////////////////////////
//Description:
// This function maps a wide-character string to a new character string
//
//Parameters:
// lpcwszStr: [in] Pointer to the character string to be converted
// lpszStr: [out] Pointer to a buffer that receives the translated string.
// dwSize: [in] Size of the buffer
//
//Return Values:
// TRUE: Succeed
// FALSE: Failed
//
//Example:
// MByteToWChar(szW,szA,sizeof(szA)/sizeof(szA[0]));
//////////////////////////////////////////////////////////////////////////////
BOOL WCharToMByte(LPCWSTR lpcwszStr, LPSTR lpszStr, DWORD dwSize)
{
DWORD dwMinSize;
dwMinSize = WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,NULL,0,NULL,FALSE);
if(dwSize < dwMinSize)
{
return FALSE;
}
WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,lpszStr,dwSize,NULL,FALSE);
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
//Description:
// This function maps a character string to a wide-character (Unicode) string
//
//Parameters:
// lpcszStr: [in] Pointer to the character string to be converted
// lpwszStr: [out] Pointer to a buffer that receives the translated string.
// dwSize: [in] Size of the buffer
//
//Return Values:
// TRUE: Succeed
// FALSE: Failed
//
//Example:
// MByteToWChar(szA,szW,sizeof(szW)/sizeof(szW[0]));
///////////////////////////////////////////////////////////////////////////////
BOOL MByteToWChar(LPCSTR lpcszStr, LPWSTR lpwszStr, DWORD dwSize)
{
// Get the required size of the buffer that receives the Unicode
// string.
DWORD dwMinSize;
dwMinSize = MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, NULL, 0);
if(dwSize < dwMinSize)
{
return FALSE;
}
// Convert headers from ASCII to Unicode.
MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, lpwszStr, dwMinSize);
return TRUE;
}
很少有人提及到下面的兩個函數size_t wcstombs(char (&
mbstr)[size], const wchar_t *
wcstr, size_t
count );
size_t mbstowcs( wchar_t (&
wcstr)[size], const char *
mbstr, size_t
count ); 以為只能用在COM中,其實不然,還可以用在WM5.0和Wince平臺;
用這兩個函數的好處就是一行代碼就可以完成轉換。要注意的是在用wcstombs函數時第三個參數必須是第二個參數長度的兩倍,用mbstowcs是第三個參數是第二個參數的長度,wcstombs可以完成WCHAR、TCHAR、CString向char*的轉換。
CString是MFC中的類,可以用WCHAR、TCHAR、cahr*直接初始化和賦值;值得一提的是在WM5.0、WCE平臺稍微有些和其他windows平臺不同的是,雖然函數傳參時無論WCHAR/TCHAR、char*都可以轉成CString作參數傳遞,因為函數傳參實際是一個賦值的過程。但是在輸出到設備上時,還必須用mbstowcs函數來轉換。
雖然Wce和Mobile平臺上只能用Unicode,但是讀寫文件時依然可以用標準C的文件操作函數,但是讀寫文件時用的字符要一致。
關于VS2008平臺字符串轉換,請看
http://msdn.microsoft.com/zh-cn/library/ms235631(VS.80).aspx