DISC-O
DISC-O

Reputation: 332

Convert comma separated string of ints into a List C++/cli

My starting point is a string separated by commas, containing a variable number of integers e.g.:

System::String^ tags=gcnew String("1,3,5,9");

Now I would like - with the least amount of steps possible - convert this string into a Integer list:

List<System::Int32>^  taglist= gcnew List<System::Int32>();//to contain 1,3,5,9

Additionally, after manipulating the list, I need to export it back to a string at the end of the day. I saw the question being asked for C# here but not for C++ which will be slightly different.

I tried directly initialize using the string, but that failed. I also tried .Split but that produces strings. I also dont want to do any complicated streamreader stuff. The answer in the link must have an equivalent for C++/cli.

Upvotes: 0

Views: 619

Answers (1)

Sergey Shevchenko
Sergey Shevchenko

Reputation: 570

As it mentioned in a comments you can use Split to convert the string to an array of strings, then you can use Array::ConvertAll to convert to an array of int values and after manipulating the values you can ise String::Join to convert an array of ints to a single string.

Here's a code sample:

String^ tags = gcnew String("1,3,5,9");
String^ separator = ",";
array<String^>^ tagsArray = tags->Split(separator->ToCharArray());

array<int>^ tagsIntArray = Array::ConvertAll<String^, int>(tagsArray,
    gcnew Converter<String^, int>(Int32::Parse));

// Do your stuff

String^ resultString = String::Join<int>(separator, tagsIntArray);

Upvotes: 1

Related Questions