Alex Rivera | Logout

Concatenating an array of strings to "string1, string2 or string3"

Asked 2009-04-06T14:28:22.397
11

Consider the following code:

string[] s = new[] { "Rob", "Jane", "Freddy" };

string joined = string.Join(", ", s);

// joined equals "Rob, Jane, Freddy"

For UI reasons I might well want to display the string "Rob, Jane or Freddy".

Any suggestions about the most concise way to do this?

Edit

I am looking for something that is concise to type. Since I am only concatenating small numbers (<10) of strings I am not worried about run-time performance here.

Edit
Report

1 Answer

3

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 ");
answered 2009-04-06T15:00:51.070

Your Answer