Logo

Programming-Idioms

Create the end-user text, s, specifying the contents of collection a.

For example, "A", "A and B", "A, B, and C", etc.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
import static java.lang.String.join;
import static java.util.Arrays.copyOfRange;
int n = a.length - 1;
String s = switch (n) {
    case 0 -> a[0];
    case 1 -> a[0] + " and " + a[1];
    default -> {
        s = join(", ", copyOfRange(a, 0, n));
        yield s + ", and " + a[n];
    }
};
import static java.text.MessageFormat.format;
String s = format("{0,list}", a);
sysutils
  if Length(a) > 1 then
  begin
    s := String.Join(', ', a, 0, Length(a)-1);
    s := s + ' and ' + a[High(a)]
  end
  else
  begin
    if Length(a) > 0 then
      s := a[0]
    else
      s :='';
  end;
match len(a):
    case 1: s = a[0]
    case 2: s = ' and '.join(a)
    case _:
        s = ', '.join(a[:-1])
        s = s + ', and ' + a[-1]
class List:
    def __init__(self):
        self.m = []
    def apply(self, /, *x, y='', z=''):
        self.m.append((x, y, z))
    def parse(self, x):
        x = [*map(str, x)]
        for a, y, z in self.m:
            for i in a: x[i] = y + x[i] + z
        return ''.join(x)
x = List()
match n := len(a):
    case 1: ...
    case 2: x.apply(0, z=' and ')
    case _:
        x.apply(*range(n - 1), z=', ')
        x.apply(-1, y='and ')
s = x.parse(a)
remainder, last = a[..-2], a[-1]
s = remainder.join(", ") + "#{' and ' unless remainder.empty?}" + last.to_s