Home  >  Article  >  Backend Development  >  How do you convert a vector of integers to a delimited string in C ?

How do you convert a vector of integers to a delimited string in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 19:51:02594browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn