1. 常见字符串类型
在C++中,常见的字符串类型包括:
CString:MFC中的字符串类,通常用于Windows应用程序开发。
std::string:标准C++字符串类,用于处理ANSI字符串。
std::wstring:标准C++字符串类,用于处理Unicode字符串(wchar_t类型)。
*char(字符指针):C风格的字符串。
*wchar_t(宽字符指针):C风格的宽字符串。
2. CString和std::string之间的转换
2.1 CString转换为std::string
如果MFC是按照ANSI编译的,可以将CString直接转换为std::string:
CString cStr = "Hello, world!";
std::string stdStr(cStr);
//或者
std::string strStd = strC.GetString(); // 如果CString是ANSI字符串,可以直接转换
如果MFC是按照Unicode编译的,需要先将CString转换为ANSI字符串,然后再转换为std::string:
CString cStr = L"Hello, world!";//_T("Hello, world!");
std::string stdStr = CW2A(cStr); // CW2A在Unicode模式下转换
或者使用CT2W:
CString cStr = CT2W(stdStr.c_str());
3. 其他常见类型字符串转换
3.1 char*转换为std::string
char* psz = "Hello, World!";
std::string str(psz);
3.2 std::string转化char*
std::string str = "Hello, World!";
char* psz = const_cast<char*>(str.c_str());
3.3 wchar_t*转换为std::wstring
wchar_t* wsz = L"Hello, World!";
std::wstring wstr(wsz);
3.4 std::wstring转换为wchar_t*
std::wstring wstr = L"Hello, World!";
wchar_t* wsz = const_cast<wchar_t*>(wstr.c_str());
3.5 ANSI字符串与Unicode字符串之间的转换
在Windows编程中,常用MultiByteToWidechar和WideCharToMultiByte函数进行ANSI和Unicode字符串之间的转换。
ANSI转Unicode:
char* psz Ansi = "Hello, World!";
wchar_t* wszUnicode = new wchar_t[strlen(pszAnsi) + 1];
MultiByteToWideChar(CP_ACP, 0, pszAnsi, strlen(pszAnsi), wszUnicode, strlen(pszAnsi) + 1);
Unicode转ANSI:
wchar_t* wszUnicode = L"Hello, World!";
char* pszAnsi = new char[wcslen(wszUnicode) + 1];
WideCharToMultiByte(CP_ACP, 0, wszUnicode, wcslen(wszUnicode), pszAnsi, wcslen(wszUnicode) + 1, NULL, NULL);
4. 注意事项
字符集的选择:在Windows编程中,确保项目设置中选择了正确的字符集(如“Use Unicode Character Set”)。
内存管理:在使用new分配内存时,记得释放内存以避免内存泄漏。
错误处理:在使用API函数(如MultiByteToWideChar和WideCharToMultiByte)时,检查返回值以确保转换成功。
版权声明,转载原文出处链接。原文链接:https://blog.youkuaiyun.com/X_StarrySky_God/article/details/145706030