112

Is there a way to do the opposite of String.Split in .Net? That is, to combine all the elements of an array with a given separator.

Taking ["a", "b", "c"] and giving "a b c" (with a separator of " ").

UPDATE: I found the answer myself. It is the String.Join method.

budi
  • 6,351
  • 10
  • 55
  • 80
robintw
  • 27,571
  • 51
  • 138
  • 205
  • 17
    I have forgotten, searched for, and found this question / answer 3 times now in the last year. – sparks Jan 28 '13 at 22:25
  • 10
    This can get confusing, since LINQ gives `string[]` a Join method that does something completely different. – yoozer8 May 03 '13 at 18:22

3 Answers3

143

Found the answer. It's called String.Join.

qwlice
  • 556
  • 7
  • 23
robintw
  • 27,571
  • 51
  • 138
  • 205
18

You can use String.Join:

string[] array = new string[] { "a", "b", "c" };
string separator = " ";
string joined = String.Join(separator, array); // "a b c"

Though more verbose, you can also use a StringBuilder approach:

StringBuilder builder = new StringBuilder();

if (array.Length > 0)
{
    builder.Append(array[0]);
}
for (var i = 1; i < array.Length; ++i)
{
    builder.Append(separator);
    builder.Append(array[i]);
}

string joined = builder.ToString(); // "a b c"
budi
  • 6,351
  • 10
  • 55
  • 80
0

using string.join():

string[] array = new string[] { "a", "b", "c" };
string separator = ",";
string joined = String.Join(separator, array); // "a,b,c"

using StringBuilder

StringBuilder namesSB = new StringBuilder();
namesSB.AppendJoin(separator, array);
string joined =namesSB.ToString();
Mahdi Rostami
  • 305
  • 4
  • 24