MFC Cstring类的拆分功能

时间:2010-06-30 07:27:45

标签: visual-c++ mfc

如何在vc ++中通过分隔符拆分CString对象?

例如,我有一个string

“一+二+三+四”

CString变量。

4 个答案:

答案 0 :(得分:30)

this question类似:

CString str = _T("one+two+three+four");

int nTokenPos = 0;
CString strToken = str.Tokenize(_T("+"), nTokenPos);

while (!strToken.IsEmpty())
{
    // do something with strToken
    // ....
    strToken = str.Tokenize(_T("+"), nTokenPos);
}

答案 1 :(得分:21)

CString sInput="one+two+three";
CString sToken=_T("");
int i = 0; // substring index to extract
while (AfxExtractSubString(sToken, sInput, i,'+'))
{   
   //.. 
   //work with sToken
   //..
   i++;
}

AfxExtractSubString on MSDN

答案 2 :(得分:9)

int i = 0;
CStringArray saItems;
for(CString sItem = sFrom.Tokenize(" ",i); i >= 0; sItem = sFrom.Tokenize(" ",i))
{
    saItems.Add( sItem );
}

答案 3 :(得分:8)

在CS6中,CString没有Tokenize方法,你可以按照strtok函数及其朋友。

#include <tchar.h>

// ...

CString cstr = _T("one+two+three+four");
TCHAR * str = (LPCTSTR)cstr;
TCHAR * pch = _tcstok (str,_T("+"));
while (pch != NULL)
{
  // do something with token in pch
  // 
  pch = _tcstok (NULL, _T("+"));
}

// ...