Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split functionality for MFC Cstring Class

Tags:

visual-c++

mfc

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.

like image 680
Dharma Avatar asked Jun 30 '10 07:06

Dharma


People also ask

What is MFC CString?

Advertisements. Strings are objects that represent sequences of characters. The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character '\0'.

How do you convert CString to float in MFC?

CString pi = "3.14"; return _ttof(pi); Reading a string value and parse/convert it to float allows you to locate the error when there is one. All you need is a help of a C Run-time function: strtod() or atof().

How do you use CString?

To use a CString object as a C-style string, cast the object to LPCTSTR . In the following example, the CString returns a pointer to a read-only C-style null-terminated string. The strcpy function puts a copy of the C-style string in the variable myString .


3 Answers

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

// ...
like image 148
sje397 Avatar answered Sep 25 '22 14:09

sje397


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.

like image 23
Dharma Avatar answered Sep 25 '22 14:09

Dharma


int i = 0;
CStringArray saItems;
for(CString sItem = sFrom.Tokenize(" ",i); i >= 0; sItem = sFrom.Tokenize(" ",i))
{
    saItems.Add( sItem );
}
like image 41
Flubert Avatar answered Sep 28 '22 14:09

Flubert