Home > Article > Backend Development > How do you convert a vector of integers to a delimited string in C ?
Join Vector of Integers into a Delimited String
In C , converting a vector of integers into a string delimited by a specific character can be achieved through various approaches.
Using a Stringstream
One method involves using a std::stringstream, as shown in the following code:
<code class="cpp">#include <sstream> //... std::stringstream ss; for (size_t i = 0; i < v.size(); ++i) { if (i != 0) ss << ","; ss << v[i]; } std::string s = ss.str();
Here, the stringstream object ss is used to sequentially append the integers to the string while inserting a comma as the delimiter.
Utilizing std::for_each
Alternatively, you can use the std::for_each algorithm along with a custom lambda function:
<code class="cpp">#include <algorithm> #include <sstream> //... std::stringstream ss; std::for_each(v.begin(), v.end(), [&ss](int i) { if (ss.str().size() != 0) ss << ","; ss << i; }); std::string s = ss.str();</code>
In this approach, the lambda function inserts a comma when iterating over subsequent elements, ensuring the correct delimiter placement.
The above is the detailed content of How do you convert a vector of integers to a delimited string in C ?. For more information, please follow other related articles on the PHP Chinese website!