C++实现CString和string的互相转换

2014-11-24 08:10:16 · 作者: · 浏览: 2

CString->std::string 例子:


CString strMfc=“test“;


std::string strStl;


strStl=strMfc.GetBuffer(0);


unicode情形下:


CStringW strw = _T("test");


CStringA stra(strw.GetBuffer(0));


strw.ReleaseBuffer();


std::string imgpath=stra.GetBuffer(0);


stra.ReleaseBuffer();


std::string->CString 例子:


CString strMfc;


std::string strStl=“test“;


strMfc=strStl.c_str();


AfxExtractSubString是截取字符串的函数,很好用,不过美中不足的地方在与它只能使用单个字符作为分割符。


但是这种情况在很多时候都行不通,如果分割符需要是两个字符以上呢?


之前因为这个问题试了很久,也在网上搜索过。不过可惜的是,网上的大部分关于VC截取字符串的文章都是那么同样的几篇,都是写的满复杂然后可以实现了AfxExtractSubString功能而已的,也就是只能用单个字符截取,但是标题却写着用字符串截取字符串,好笑!


不找了,自己写吧。CString里面有Find,然后再组成数组。


void Split(CString source, CStringArray& dest, CString division)
{
dest.RemoveAll();
int pos =0;
int pre_pos =0;
while( -1!= pos ){
pre_pos
= pos;
pos
= source.Find(division,(pos+1));
dest.Add(source.Mid(pre_pos,(pos
-pre_pos)));
}


}


CString source是需要截取的原字符串,

CStringArray& dest 是最终结果的数组

CString division 是用来做分割符的字符串