c++各種字串互轉(char*、wchar_t*、CString、string、wstring、LPCWSTR)

大力水手008發表於2024-06-08
 1 //字串轉換宏
 2 //簡寫意思: C: const, T: Cstring, W: wstring, A: string
 3 
 4 //Cstring 轉 wchar_t*:  
 5 wchar_t* p = cstr.AllocSysString()
 6 
 7 //Cstring 轉 string : str=CT2A(cstr)
 8 #define CSTR2STR(cstr)   CT2A(cstr)
 9 
10 //Cstring 轉 wstring: wstr= cstr;
11 #define CSTR2WSTR(cstr)   (cstr)
12 
13 //string 轉 char* ch:  
14 char* ch=str.c_str();
15 
16 //string 轉 Cstring : cstr=CA2T(str.c_str())
17 #define STR2CSTR(str)   CA2T(str.c_str())
18 
19 //string 轉 wstring: wstr=CA2W(str.c_str())
20 #define STR2WSTR(str)   CA2W(str.c_str())
21 
22 //wstring 轉 char* ch:  
23 char* ch=wstr.c_str();
24 
25 //wstring 轉 string: str=CW2A(wstr.cstr())
26 #define WSTR2STR(wstr)   CW2A(wstr.c_str())
27 
28 //wstring 轉 Cstring: CW2T(wstr.c_str())
29 #define WSTR2CSTR(wstr)   CW2T(wstr.c_str())
30 
//函式 31 // string 轉 wstring 32 wstring str2wstr(const string& str) 33 { 34 wstring wstr; 35 int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0); 36 TCHAR* buffer = new TCHAR[len + 1]; 37 MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len); 38 buffer[len] = '\0'; 39 wstr.append(buffer); 40 delete[] buffer; 41 return wstr; 42 } 43 44 //wstring 轉 string 45 string wstr2str(const wstring& wstr) 46 { 47 string str; 48 int len = WideCharToMultiByte (CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0,NULL,NULL); 49 char* buffer = new char[len + 1]; 50 WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len,NULL,NULL); 51 buffer[len] = '\0'; 52 str.append(buffer); 53 delete[] buffer; 54 return str; 55 } 56 57 //string 轉成 LPCWSTR 58 LPCWSTR stringToLPCWSTR(std::string orig) 59 { 60 size_t origsize = orig.length() + 1; 61 const size_t newsize = 100; 62 size_t convertedchars = 0; 63 wchar_t* wcstring = (wchar_t*)malloc(sizeof(wchar_t) * (orig.length() - 1)); 64 mbstowcs_s(&convertedchars, wcstring, origsize, orig.c_str(), _TRUNCATE); 65 return wcstring; 66 } 67   

相關文章