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.

4 Answers 4

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, Tokenize is not supported in VC6 MFC, But supported in ATL
You should probably add that requirement to the question.
The docs for CStringT::Tokenize() 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.
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.

4 Comments

That's one problem with crappy OO and poor APIs - functions all over the place :) Good find.
You can answer your own question. It's in the FAQ.
I would change the comma separator to a plus-sign, or the example won't work.
Thanks, but does this approach allow for empty tokens? Eg: "one++three+four"
12
int i = 0;
CStringArray saItems;
for(CString sItem = sFrom.Tokenize(" ",i); i >= 0; sItem = sFrom.Tokenize(" ",i))
{
    saItems.Add( sItem );
}

Comments

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

// ...

1 Comment

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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.