Home > Backend Development > C++ > 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
Release: 2024-11-03 19:51:02
Original
677 people have browsed it

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();
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template