views:

301

answers:

2

Hi all,

I have a vector of string and I intend to join these strings into a single string, separated by a space. For example, if my vector contains the values: sample string for this example I want the output to be "sample string for this example".

Need any of your input on what is the simplest way of achieving this?

Thanks

+10  A: 
#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;
Alex B
It's a shame about the need to trim the trailing space though.
the_mandrill
It looks like that's one of the things that boost::join does for you: http://stackoverflow.com/questions/1833447/a-good-example-for-boostalgorithmjoin
the_mandrill
+3  A: 

boost::join

Without a good example, boost::join is a world of pain. The documentation assumes at least a litle familiarity with the Boost Range library.
Dan Hook