一、CString轉String函數
CString是MFC(Microsoft Foundation Class)中提供的一種字元串類,而String是C++11標準中的字元串類。在兩者之間進行轉換是很常見的操作。可以使用CString::GetString函數將CString對象轉換為char*類型,然後再將char*類型轉換為string類型。
CString cstr = "Hello World!";
std::string str(cstr.GetString());
std::cout << str << std::endl;
在使用GetString函數時需要注意,如果CString對象被修改,那麼返回的指針也會指向修改後的字元串,因此必須保證在使用指針之前CString對象不會被修改。
二、CString轉char數組
使用ConvertUnicodeToMultiByte函數將CString對象轉換為char數組。
CString cstr = "Hello World!";
char s[100];
WideCharToMultiByte(CP_ACP, NULL, cstr, -1, s, 100, NULL, NULL);
std::cout << s << std::endl;
其中WideCharToMultiByte是Windows API中將Unicode編碼的字元轉換為多位元組字符集的函數。
三、CString轉String utf8
使用CT2CA函數將CString對象轉換為char*類型,然後再將char*類型轉換為string類型,CT2CA 默認將CString轉換為UTF-8字元串。
CString cstr = "Hello World!";
std::string utf8str(CT2CA(cstr));
std::cout << utf8str << std::endl;
四、CString轉String出錯
CString到string的轉換可能會出現亂碼,特別是在多位元組字符集(如GBK)中常常出現這種情況。如果出現亂碼,最好的解決辦法是使用Unicode字符集。
如果一定要使用多位元組字符集,可以先將CString轉換為wchar_t數組,再將wchar_t數組轉換為char數組,並指定正確的代碼頁。
CString cstr = "你好世界!";
wchar_t wsz[100];
wcscpy_s(wsz, cstr);
char s[100];
WideCharToMultiByte(CP_ACP, NULL, wsz, -1, s, 100, NULL, NULL);//這裡的-1 是因為WideCharToMultiByte函數在 NULL字元時能夠自己計算長度
std::cout << s << std::endl;
五、CString轉String^
CString到String^可以使用marshal_as函數進行轉換,需要包含頭文件msclr/marshal_cppstd.h。
#include
CString cstr = "Hello World!";
String^ str = msclr::interop::marshal_as<String^>(CString(cstr));
Console::WriteLine(str);
六、CString轉char
將CString對象轉換為char類型可以使用(LPCTSTR)強制轉換。
CString cstr = "H";
char c = (LPCTSTR)cstr;
std::cout << c << std::endl;
七、CString轉double
將CString對象轉換為double類型可以使用_tstof函數。
CString cstr = "3.1415926";
double pi = _tstof(cstr);
std::cout << pi << std::endl;
八、CString轉換為String
使用CT2T函數將CString對象轉換為CT2T<CString, strtype>類型,然後再通過ToString函數將其轉換為String類型。
CString cstr = "Hello World!";
String^ str = gcnew String(CT2T<CString, strtype>(cstr).ToString());
Console::WriteLine(str);
九、CString轉byte數組
使用wstring類型臨時轉換,然後使用reinterpret_cast強制轉換為unsigned char*類型的指針即可。
CString cstr = "Hello World!";
std::wstring wstr = CT2W(cstr);
unsigned char* bytes = reinterpret_cast(wstr.c_str());
int len = wstr.size() * sizeof(wchar_t);
for (int i = 0; i < len; ++i)
{
std::cout << (int)bytes[i] << " ";
}
std::cout << std::endl;
總之,CString到String的轉換雖然看起來很簡單,但是卻需要注意很多細節。希望本文能夠幫助到需要進行CString到String轉換的開發者。
原創文章,作者:RDEI,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/150014.html
微信掃一掃
支付寶掃一掃