tags:

views:

176

answers:

3

How to Split a CString object by delimeter in vc++? for example i have a string value "one+two+three+four" into a CString varable.

A: 

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);
}
sje397
Hi, Tokenize is not supported in VC6 MFC, But supported in ATL
Dharma
You should probably add that requirement to the question.
sje397
@mmonem Cheers. Fixed.
sje397
A: 

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

// ...
sje397
A: 
CString sInput="one+two+three";
CString sToken=_T("");
int i = 0; // substring index to extract
while (AfxExtractSubString(sToken, sInput, i,','))
{   
   //.. 
   //work with sToken
   //..
   i++;
}
Dharma
That's one problem with crappy OO and poor APIs - functions all over the place :) Good find.
sje397
Please dont answer your own question. Rather update the question or provide the comment
ckv
You can answer your own question. It's in the FAQ.
sje397