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

MFC程序中在OpenFileDialog里面,经常涉及到CString到标准库的string类的转换。

以下是转载的内容:

(1) 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();


(2)std::string->CString  

例子:

CString strMfc;

std::string strStl=“test“;

strMfc=strStl.c_str();

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

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

CString里面有Find,然后再组成数组。

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

}

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

CStringArray& dest 是最终结果的数组

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


转自:http://www.bianceng.cn/Programming/cplus/201305/36585.htm

猜你喜欢

转载自blog.csdn.net/xfijun/article/details/51436519