Split functionality for MFC Cstring Class

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.


Similar to 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);
}

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

In VC6, where CString does not have a Tokenize method, you can defer to the strtok function and it's friends.

#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("+"));
}

// ...

Tags:

Visual C++

Mfc