Logo

Programming-Idioms

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

Idiom #360 Create a formatted list

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

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

#include <string>
int n {size(a)};
string s;
if (n == 1) s = a[0];
else if (n == 2)
    s = a[0] + " and "s + a[1];
else {
    int i {};
    s = a[i++];
    --n;
    while (i not_eq n)
        s += ", "s + a[i++];
    s += ", and "s + a[n];
}
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 set(self, /, *i, a='', b=''):
        self.m.append((i, a, b))
    def to_string(self, x):
        f = lambda: a + x[i] + b
        for i, a, b in self.m:
            for i in i: x[i] = f()
        return ''.join(x)
x = List()
match n := len(a):
    case 1: ...
    case 2: x.set(0, b=' and ')
    case _:
        x.set(*range(n - 1), b=', ')
        x.set(-1, a='and ')
s = x.to_string(a)
remainder, last = a[..-2], a[-1]
s = remainder.join(", ") + "#{' and ' unless remainder.empty?}" + last.to_s

New implementation...
< >
reilas