##實戰c++中的string系列--std::string與MFC中CString的轉換
搞過MFC的人都知道cstring,給我們提供了很多便利的方法。
CString 是一種很有用的數據類型。它們很大程度上簡化了MFC中的許多操作,使得MFC在做字符串操作的時候方便了很多。不管怎樣,使用CString有很多特殊的技巧,特別是對于純C背景下走出來的程序員來說有點難以學習。
但是很多情況下,我們還是需要cstring和string的轉換。?
分兩步:?
1把cstring轉為char數組?
2根據char數組,構造自己的string(記得釋放內存)
~~~
std::string CStringToSTDStr(const CString& theCStr)
{
const int theCStrLen = theCStr.GetLength();
char *buffer = (char*)malloc(sizeof(char)*(theCStrLen+1));
memset((void*)buffer, 0, sizeof(buffer));
WideCharToMultiByte(CP_UTF8, 0, static_cast<cstring>(theCStr).GetBuffer(), theCStrLen, buffer, sizeof(char)*(theCStrLen+1), NULL, NULL);
std::string STDStr(buffer);
free((void*)buffer);
return STDStr;
}
~~~
而string轉cstring那就很輕松了:
~~~
string str="abcde";
CString cstr(str.c_str());
~~~
[](http://blog.csdn.net/wangshubo1989/article/details/50274079#)[](http://blog.csdn.net/wangshubo1989/article/details/50274079# "分享到QQ空間")[](http://blog.csdn.net/wangshubo1989/article/details/50274079# "分享到新浪微博")[](http://blog.csdn.net/wangshubo1989/article/details/50274079# "分享到騰訊微博")[](http://blog.csdn.net/wangshubo1989/article/details/50274079# "分享到人人網")[](http://blog.csdn.net/wangshubo1989/article/details/50274079# "分享到微信")
- 前言
- string與整型或浮點型互轉
- 指定浮點數有效數字并轉為string
- string的替換、查找(一些與路徑相關的操作)
- string的分割、替換(類似string.split或是explode())
- string的初始化、刪除、轉大小寫(construct erase upper-lower)
- string的遍歷(使用下標還是iterator)
- std::string與MFC中CString的轉換
- string到LPCWSTR的轉換
- std:vector<char> 和std:string相互轉換(vector to stringstream)
- CDuiString和string的轉換(duilib中的cduistring)
- string的連接(+= or append or push_back)
- 函數返回局部變量string(引用局部string,局部string的.c_str()函數)
- 將string用于switch語句(c++做C#的事兒, switch中break還是return厲害)
- 不要使用memset初始化string(一定別這么干)