VC++编程中经常遇到不同编码编码的字符串之间需要转换的情况,以下简单提供几个不同编码字符串之间的转换函数:
ANSI 字符串和Unicode字符串之间的转换
//Convert wide char string to ANSI stringBOOL WCharToMByte(LPCWSTR lpcwszStr,Std::string &str){ DWORD dwMinSize=0; LPSTR lpszStr=NULL; dwMinSize= WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,NULL,0,NULL,FALSE); if(0==dwMinSize) { return FALSE; } lpszStr=new char[dwMinSize]; WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,lpszStr,dwMinSize,NULL,FALSE); str=lpszStr; delete []lpszStr; return TRUE;}//Convert ANSI string to wide char stringBOOL MByteToWChar(LPWSTR lpcwszStr,std::string str){ size_t size=str.length(); wchar_t *buffer=new wchar_t[size+1]; MultiByteToWideChar(CP_ACP,NULL,str.c_str(),size,buffer,size*sizeof(wchar_t)); buffer[size]=0; lpcwszStr=buffer; delete buffer; return TRUE;}