4

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?

Camille Goudeseune
  • 2,934
  • 2
  • 35
  • 56
Shree
  • 4,627
  • 6
  • 37
  • 49

2 Answers2

14
#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
  • 82,554
  • 44
  • 203
  • 280
4

boost::join

  • 1
    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 Dec 02 '09 at 14:55