Home >Backend Development >C++ >How to Convert a Vector of Integers to a Comma-Separated String in C ?

How to Convert a Vector of Integers to a Comma-Separated String in C ?

DDD
DDDOriginal
2024-11-03 19:39:03262browse

How to Convert a Vector of Integers to a Comma-Separated String in C  ?

Converting a Vector of Integers to a Comma-Separated String

Transforming a vector of integers into a string separated by commas is a common task in programming. In Python, the elegance of this process is showcased in the provided example.

In C , however, the conversion is not as straightforward due to limitations in its syntax. One viable approach is utilizing a stringstream, as demonstrated below:

<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();</code>

Alternatively, you can employ the std::for_each function for a more compact solution:

The above is the detailed content of How to Convert a Vector of Integers to a Comma-Separated 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