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.
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);
}
Tokenize(). For instance, "+one+two+three+four" would not yield the expected result of 5 substrings.CString sInput="one+two+three";
CString sToken=_T("");
int i = 0; // substring index to extract
while (AfxExtractSubString(sToken, sInput, i,'+'))
{
//..
//work with sToken
//..
i++;
}
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("+"));
}
// ...
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();