2

I need to concatenate a list of MFC CString objects into a single CSV string. .NET has String.Join for this task. Is there an established way to do this in MFC/C++?

2 Answers 2

5

The + operator is overloaded to allow string concatenation. I'd suggest take a look at the documentation on MSDN:

Basic CString Operations has the following example:

CString s1 = _T("This ");        // Cascading concatenation
s1 += _T("is a ");
CString s2 = _T("test");
CString message = s1 + _T("big ") + s2;  
// Message contains "This is a big test".

If you want the strings to be comma-separated, just add the commas yourself.

Sign up to request clarification or add additional context in comments.

Comments

0

Iterate through the list of CString objects invoking the AppendFormat method.

//  Initialize CStringList
CStringList cslist ;
cslist.AddTail( "yaba" ) ;
cslist.AddTail( "daba" ) ;
cslist.AddTail( "doo"  ) ;

//  Join
CString csv ;
for ( POSITION pos = cslist.GetHeadPosition() ; pos != NULL ; )
    csv.AppendFormat( ",%s" , cslist.GetNext( pos ) ) ;
csv.Delete( 0 ) ;  //  remove leading comma

1 Comment

Deleting the first char of a string has got to be the most expensive operation you can perform. Switch the comma around and delete the last char. Or just don't generate extra commas.

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.