The most memory efficient and scalable would be using a StringBuilder
and precalculating the length of the final string to elliminate buffer reallocations. (This is similar to how the String.Concat
method works.)
public static string Join(string[] items, string separator, string lastSeparator) {
int len = separator.Length * (items.Length - 2) + lastSeparator.Length;
foreach (string s in items) len += s.Length;
StringBuilder builder = new StringBuilder(len);
for (int i = 0; i < items.Length; i++) {
builder.Append(items[i]);
switch (items.Length - i) {
case 1: break;
case 2: builder.Append(lastSeparator); break;
default: builder.Append(separator); break;
}
}
return builder.ToString();
}
Usage:
string joined = Join(s, ", ", " or ");
An interresting solution would be using a recursive algorithm. It works well for a reasonably small number of strings, but it doesn't scale very well.
public static string Join(string[] items, int index , string separator, string lastSeparator) {
return items[index++] + (index == items.Length-1 ? lastSeparator + items[index] : separator + Join(items, index, separator, lastSeparator));
}
Usage:
string joined = Join(s, 0, ", ", " or ");