This language bar is your friend. Select your favorite languages!

Idiom #53 Join a list of strings

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

Illustration
$y = join(", ", @x)
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;
#include <string.h>
#define DELIM ", "
#define L 64

char y[L] = {'\0'};

for (int i = 0; i < N; ++i)
{
    if (i && x[i][0])
        strcat(y, DELIM);
    
    strcat(y, x[i]);
}
(clojure.string/join "," '("abc" "def" "ghi") )
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
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();
}
string y = string.Join(", ", x);
import std.array;
string y = x.join(", ");
y = x.join(', ');
y = Enum.join(x, ", ")
Y = string:join(X, ",").
import "strings"
y := strings.Join(x, ", ")
import Data.List
y = intercalate ", " x
import qualified Data.Text as T
{-# LANGUAGE OverloadedStrings #-}
y :: T.Text
y = T.intercalate ", " x
y = x.join(", ");
String y = String.join(", ", x);
(setf y (format nil "~{~a~^,~}" x))
(defvar y (format nil "~{~A~^, ~}" x))
y = table.concat(x, ", ")
$y = implode(", ", $x);
var
  _x: Array of string;
  _y: String;
  i: Integer;
begin
  _y := ''; //initialize result to an empy string
  // assume _x is initialized to contain some values
  for i := Low(_x) to High(_x) do
  begin
    _y := _y + _x[i];
    if i < High(_x) then _y := _y + ';';
  end;
end;
y = ', '.join(str(v) for v in x)
y = ', '.join(x)
y = x.join(", ")
let y = x.connect(", ");
val y = x.mkString(",")
(define y
  (foldr (lambda (a b)
           (if (string=? b "")
               a
               (string-append a ", " b)))
         ""
         x))

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms