Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 289
Shree Avatar asked Dec 04 '22 15:12

Shree


1 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;
like image 122
Alex B Avatar answered Dec 09 '22 15:12

Alex B