在做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
#include "stdafx.h" #include "CStringToolEx.h" #include <cstringt.h> // // CStringA转CStringW // CStringW CStrA2CStrW(const CStringA &cstrSrcA) { int len = MultiByteToWideChar(CP_ACP, 0, LPCSTR(cstrSrcA), -1, NULL, 0); wchar_t *wstr = new wchar_t[len]; memset(wstr, 0, len*sizeof(wchar_t)); MultiByteToWideChar(CP_ACP, 0, LPCSTR(cstrSrcA), -1, wstr, len); CStringW cstrDestW = wstr; delete[] wstr; return cstrDestW; } // // CStringW转CStringA // CStringA CStrW2CStrA(const CStringW &cstrSrcW) { int len = WideCharToMultiByte(CP_ACP, 0, LPCWSTR(cstrSrcW), -1, NULL, 0, NULL, NULL); char *str = new char[len]; memset(str, 0, len); WideCharToMultiByte(CP_ACP, 0, LPCWSTR(cstrSrcW), -1, str, len, NULL, NULL); CStringA cstrDestA = str; delete[] str; return cstrDestA; }
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);