28

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.

Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112
Dharma
  • 837
  • 1
  • 9
  • 14

4 Answers4

42

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);
}
Community
  • 1
  • 1
sje397
  • 41,293
  • 8
  • 87
  • 103
  • 1
    Hi, Tokenize is not supported in VC6 MFC, But supported in ATL – Dharma Jun 30 '10 at 09:07
  • You should probably add that requirement to the question. – sje397 Jun 30 '10 at 09:18
  • 4
    [The docs for CStringT::Tokenize()](http://msdn.microsoft.com/en-us/library/k4ftfkd2.aspx) say that the function skips leading delimiters, so if you truly want to split a string and not ignore empty substrings, then I would say that you can't use `Tokenize()`. For instance, "+one+two+three+four" would not yield the expected result of 5 substrings. – herzbube Feb 24 '12 at 11:11
25
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.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Dharma
  • 837
  • 1
  • 9
  • 14
11
int i = 0;
CStringArray saItems;
for(CString sItem = sFrom.Tokenize(" ",i); i >= 0; sItem = sFrom.Tokenize(" ",i))
{
    saItems.Add( sItem );
}
Yuck
  • 49,664
  • 13
  • 105
  • 135
Flubert
  • 111
  • 1
  • 2
7

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

// ...
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
sje397
  • 41,293
  • 8
  • 87
  • 103
  • `TCHAR * str = (LPCTSTR)cstr` will throw a compiler error as `a value of type "LPCTSTR" cannot be used to initialize an entity of type "TCHAR *"`. You should use `TCHAR * str = cstr.GetBuffer();` – Sisir Jun 04 '19 at 10:10