Logo

Programming-Idioms

From list a, create the text s specifying the contents of a, such that items are separated by delimiter d and items containing 1 or more spaces are quoted with quote character q.
Example: "A "," B"," C ",D,E,F
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
String s = a.stream()
    .map(x -> {
        if (!x.contains(" ")) return x;
        return q + x + q;
    })
    .reduce((x, y) -> x + d + y)
    .get();
import static java.lang.String.join;
import java.util.ArrayList;
import java.util.List;
class QuotedList extends ArrayList<String> {
    String d, q;
    QuotedList(String d, String q) {
        this.d = d;
        this.q = q;
    }
    public boolean add(String s) {
        if (s.contains(" ")) s = q + s + q;
        return super.add(s);
    }
    public String toString() {
        return join(d, this);
    }
}
QuotedList x = new QuotedList(d, q) {{
    for (var x : a) add(x);
}};
String s = x.toString();
classes
  a.Delimiter := d;
  a.QuoteChar := q;
  a.StrictDelimiter := False;
  a.AlwaysQuote := False;
  s := a.DelimitedText;
class QuotedList(list):
    def __init__(self, quotes, sep):
        super().__init__()
        self.quotes = quotes
        self.sep = sep
    def append(self, value):
        if ' ' in value:
            value = value.join(self.quotes)
        super().append(value)
    def extend(self, iterable):
        for value in iterable:
            self.append(value)
    def __str__(self):
        return self.sep.join(self)
qlist = QuotedList(q * 2, d)
qlist.extend(a)
s = str(qlist)
qlist = list(a)
for i, string in enumerate(qlist):
    if ' ' in string:
        qlist[i] = string.join(q * 2)
s = d.join(qlist)
def quoted_list(string, quotes, sep):
    def join(value, *args):
        if ' ' in value:
            value = value.join(quotes)
        if not args:
            return value
        return value + sep + join(*args)
    return join(*string)
s = quoted_list(a, q * 2, d)
s = a.map{_1.include?(" ") ? q + _1 + q : _1 }.join(d)