String concatenation

I want to combine vector<string>into one string, separated by spaces. For example,

sample
string
for
this
example

should become "sample string for this example".
What is the easiest way to do this?

+4
source share
2 answers
#include <iterator>
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>

std::vector<std::string> v;
...

std::stringstream ss;
std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(ss, " "));
std::string result = ss.str();
if (!result.empty()) {
    result.resize(result.length() - 1); // trim trailing space
}
std::cout << result << std::endl;
+13
source

boost :: join

+4
source

Source: https://habr.com/ru/post/1705952/


All Articles