Logo

Programming-Idioms

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

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"
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]);
}

x is assumed to be an array containing N null-terminated strings.

L is arbitrary, but big enough to hold the concatenated string.

New implementation...