Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • C++

Idiom #53 Join a list of strings

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

Turning the strings "eggs", "butter", "milk" into the string "eggs, butter, milk"
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
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();
}
#include <string>
#include <vector>
#include <ranges>
using namespace std::ranges;
y = x | views::join_with(',') | to<std::string>();
with Ada.Containers.Indefinite_Vectors; use Ada.Containers;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
declare
   Last : Cursor := X.Last;
   Y : Unbounded_String;
         
begin
   for C in X.Iterate loop
      Y := Y & Element (C) & (if C = Last then "" else ", ");
   end loop;
end;

New implementation...