Opposite of String.Split with separators (.net)
C#.NetArraysStringC# 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"