Shree
Shree

Reputation: 4747

Concatenating strings

I want to join a vector<string> into a single string, separated by spaces. For example,

sample
string
for
this
example

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

Upvotes: 4

Views: 2851

Answers (2)

boguscoder
boguscoder

Reputation:

boost::join

Upvotes: 4

Alex B
Alex B

Reputation: 84822

#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;

Upvotes: 14

Related Questions