Logo

Programming-Idioms

History of Idiom 53 > diff from v50 to v51

Edit summary for version 51 by programming-idioms.org:
[Cpp] Comments/summary

Version 50

2019-04-12, 22:29:25

Version 51

2019-04-14, 17:37:12

Idiom #53 Join a list of strings

Concatenate elements of string list x joined by the separator ", " to create a single string y.

Illustration

Idiom #53 Join a list of strings

Concatenate elements of string list x joined by the separator ", " to create a single string y.

Illustration
Imports
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
Imports
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
Code
std::vector<std::string> x;
std::string y;
const char* const delim = ", ";

switch (x.size())
{
	case 0: y = "";   break;
	case 1: y = x[0]; break;
	default:
		std::ostringstream os;
		std::copy(x.begin(), x.end() - 1,
			std::ostream_iterator<std::string>(os, delim));
		os << *x.rbegin();
		y = os.str();
}
Code
std::vector<std::string> x;
std::string y;
const char* const delim = ", ";

switch (x.size())
{
	case 0: y = "";   break;
	case 1: y = x[0]; break;
	default:
		std::ostringstream os;
		std::copy(x.begin(), x.end() - 1,
			std::ostream_iterator<std::string>(os, delim));
		os << *x.rbegin();
		y = os.str();
}
Comments bubble
add y declaration
Origin
http://stackoverflow.com/questions/5288396/c-ostream-out-manipulation/5289170#5289170
Origin
http://stackoverflow.com/questions/5288396/c-ostream-out-manipulation/5289170#5289170