string转CString
时间: 2023-11-03 17:20:56 浏览: 102
要将string类型转换为CString类型,有两种情况需要考虑:UNICODE和非UNICODE。对于非UNICODE,转换比较简单。你可以使用如下代码进行转换:
```cpp
string str = "abcde";
CString cstr(str.c_str());
```
对于UNICODE,需要进行一些额外的转换。你可以使用以下函数将WCHAR转换为ANSI:
```cpp
string CUtility::WChar2Ansi(LPCWSTR pwszSrc) {
int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL);
if (nLen <= 0) return std::string("");
char* pszDst = new char[nLen];
if (NULL == pszDst) return std::string("");
WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL);
pszDst[nLen - 1 = 0;
std::string strTemp(pszDst);
delete[] pszDst;
return strTemp;
}
```
然后,你可以按照以下方式转换:
```cpp
CString cs = _T("abcde");
string str = CGeneralUtility::WChar2Ansi(cs.GetBuffer(cs.GetLength()));
```
这样就可以将string类型转换为CString类型了。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [string 与 CString 转化](https://blog.csdn.net/red10057/article/details/6401420)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [C#实现 MFC的CString字节数组转换为C#的String](https://download.csdn.net/download/circle900617/9732544)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [string和cstring互转](https://blog.csdn.net/tianzhijiaozi19/article/details/71910843)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文