Opposite of String.Split with separators (.net)

C#.NetArraysString

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

Found the answer. It's called [String.Join](http://msdn.microsoft.com/en-us/library/System.String.Join(v=vs.110).aspx "MSDN page for String.Join").

Solution 2 - C#

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrobintwView Question on Stackoverflow
Solution 1 - C#robintwView Answer on Stackoverflow
Solution 2 - C#budiView Answer on Stackoverflow