Converting and Concatenating Strings
-
is for Managed Visual C++.NET.. Suppose I have two Strings. String1 = C://files String2 = data.txt I want to concatenate the two strings while inserting a character between them, to get a new string: C://file/data.txt Here the character is an extra "/". Once this is done, I would like to convert the new string to a char[20]. Does anyone know how to perform this task? I would be very grateful.. Thanks KBL
-
is for Managed Visual C++.NET.. Suppose I have two Strings. String1 = C://files String2 = data.txt I want to concatenate the two strings while inserting a character between them, to get a new string: C://file/data.txt Here the character is an extra "/". Once this is done, I would like to convert the new string to a char[20]. Does anyone know how to perform this task? I would be very grateful.. Thanks KBL
There are no overloaded + or += operators for Strings in MC++, so one must use the plain member functions:
String *String1 = S"C:\\files"; String *String2 = S"data.txt"; String1 = String::Concat(String1, S"\\", String2); //or much less efficiently... //String1 = String1->Insert(String1->Length, S"\\"); //String1 = String1->Insert(String1->Length, String2); char achCStr[20]; wchar_t *pGuts = PtrToStringArray(String1); int iChrs = ::WideCharToMultiByte(CP_ACP, 0, pGuts, String1->Length, achCStr, 20, NULL, NULL); achCStr[iChrs] = '\0';
PtrToStringArray() was posted earlier at http://www.codeproject.com/script/comments/forums.asp?forumid=3785&select=364715#xx364715xx[^] , and explained 2 posts earlier in that thread. String::Concat() returns a concatenated copy of between 2 and 4 strings, and since the lengths of all the Strings are calculated prior to assembling them into the returned String, should avoid multiple temporary copies usually associated with concatenation (nice!). Insert() works like strcat() when the start position is the same as the original String's length, but as you can see it requires an extra temporary String copy :(. It's undocumented, but when I do something like the above, I pass 'String1->Length+1' in WideCharToMultiByte(), which avoids having to add the terminating null character afterwards. Like CString and std::string, CLR Strings seem to always have a terminating null appended to them, and I have never seen a case where they haven't. Cheers