Programming Tips - MFC: Split a CString on a delimiter into a CStringArray

Date: 2020mar24
Language: C++
Framework: MFC

Q.  MFC: Split a CString on a delimiter into a CStringArray

A.
Using Tokenize()
void Split1(const CString strIn, const CString delim, CStringArray &a) { int position = 0; CString strToken; a.RemoveAll(); strToken = strIn.Tokenize(delim, position); a.Add(strToken); while(!strToken.IsEmpty()) { strToken = strIn.Tokenize(delim, position); a.Add(strToken); } }
Using strtok_r()
void Split2(LPCSTR in, LPCSTR delim, CStringArray &a) { LPSTR save; LPSTR p; char buf[1024]; a.RemoveAll(); lstrcpyn(buf, in, sizeof(buf)); for (p = strtok_r(buf, delim, &save); p; p = strtok_r(NULL, delim, &save)) { a.Add(p); } }
// Example use void SplitOnWhitespace(const CString in, CStringArray &a) { Cstring strWhitespace = " \n\r\t"; Split1(in, strWhitespace, a); }