在做MFC编程的时候,时常会碰到CString、CStringA、CStringW之间相互转换的问题,也即chat字符串与wchar_t字符串相互转换的问题。
现本人写了一个它们之间相互转换的函数,代码如下:
头文件CStringToolEx.h
#ifndef _CSTRING_TOOL_EX_ #define _CSTRING_TOOL_EX_ #include <cstringt.h> // // CString转CStringA // #ifndef CStrT2CStrA #ifdef _UNICODE #define CStrT2CStrA(cstr) CStrW2CStrA((cstr)) #else #define CStrT2CStrA(cstr) (cstr) #endif #endif // // CString转CStringW // #ifndef CStrT2CStrW #ifdef _UNICODE #define CStrT2CStrW(cstr) (cstr) #else #define CStrT2CStrW(cstr) CStrA2CStrW((cstr)) #endif #endif // // CStringA转CString // #ifndef CStrA2CStrT #ifdef _UNICODE #define CStrA2CStrT(cstr) CStrA2CStrW((cstr)) #else #define CStrA2CStrT(cstr) (cstr) #endif #endif // // CStringW转CString // #ifndef CStrW2CStrT #ifdef _UNICODE #define CStrW2CStrT(cstr) (cstr) #else #define CStrW2CStrT(cstr) CStrW2CStrA((cstr)) #endif #endif // // CStringA转CStringW // CStringW CStrA2CStrW(const CStringA &cstrSrcA); // // CStringW转CStringA // CStringA CStrW2CStrA(const CStringW &cstrSrcW); #endif
源文件CStringToolEx.cpp
1 #include "stdafx.h" 2 #include "CStringToolEx.h" 3 #include <cstringt.h> 4 5 // 6 // CStringA转CStringW 7 // 8 CStringW CStrA2CStrW(const CStringA &cstrSrcA) 9 { 10 int len = MultiByteToWideChar(CP_ACP, 0, LPCSTR(cstrSrcA), -1, NULL, 0); 11 wchar_t *wstr = new wchar_t[len]; 12 memset(wstr, 0, len*sizeof(wchar_t)); 13 MultiByteToWideChar(CP_ACP, 0, LPCSTR(cstrSrcA), -1, wstr, len); 14 CStringW cstrDestW = wstr; 15 delete[] wstr; 16 17 return cstrDestW; 18 } 19 20 // 21 // CStringW转CStringA 22 // 23 CStringA CStrW2CStrA(const CStringW &cstrSrcW) 24 { 25 int len = WideCharToMultiByte(CP_ACP, 0, LPCWSTR(cstrSrcW), -1, NULL, 0, NULL, NULL); 26 char *str = new char[len]; 27 memset(str, 0, len); 28 WideCharToMultiByte(CP_ACP, 0, LPCWSTR(cstrSrcW), -1, str, len, NULL, NULL); 29 CStringA cstrDestA = str; 30 delete[] str; 31 32 return cstrDestA; 33 }
使用示例:
CString cstrName = TEXT("Hello Kitty"); CStringA cstraName = CStrT2CStrA(cstrName); //CString to CStringA CStringW cstrwName = CStrT2CStrW(cstrName); //CString to CStringW ::MessageBoxA(NULL, cstraName, "CStringToolEx Test", MB_OK); ::MessageBoxW(NULL, cstrwName, L"CStringToolEx Test", MB_OK); CStringA cstraAddr = "Anhui Anqing"; CString cstrAddr = CStrA2CStrT(cstraAddr); //CStringA to CString CStringW cstrwAddr = CStrA2CStrW(cstraAddr); //CStringA to CStringW ::MessageBox(NULL, cstrAddr, TEXT("CStringToolEx Test"), MB_OK); ::MessageBoxW(NULL, cstrwAddr, L"CStringToolEx Test", MB_OK); CStringW cstrwGender = L"Male"; CString cstrGender = CStrW2CStrT(cstrwGender); //CStringW to CString CStringA cstraGender = CStrW2CStrA(cstrwGender); //CStringW to CStringA ::MessageBox(NULL, cstrGender, TEXT("CStringToolEx Test"), MB_OK); ::MessageBoxA(NULL, cstraGender, "CStringToolEx Test", MB_OK);