Logo

Programming-Idioms

History of Idiom 53 > diff from v49 to v50

Edit summary for version 50 by jerome:
[Cpp] fix bug

Version 49

2018-07-23, 11:49:19

Version 50

2019-04-12, 22:29:25

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;

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