views:

326

answers:

2

Let's say I have an array of strings:

string[] myStrings = new string[] { "First", "Second", "Third" };

I want to concatenate them so the output is:

First Second Third

I know I can concatenate them like this, but there'll be no space in between:

string output = String.Concat(myStrings.ToArray());

I can obviously do this in a loop, but I was hoping for a better way.

Is there a more succinct way to do what I want?

+23  A: 

Try this:

String output = String.Join(" ", myStrings);
Andrew Hare
perfect, thanks :)
Damovisa
+1  A: 
StringBuilder buf = new StringBuilder();
foreach(var s in myStrings)
  buf.Append(s).Append(" ");
var ss = buf.ToString().Trim();
James Black
Yep, that'll work, but I was hoping for a one-liner :)
Damovisa
One liners are overrated. :)
James Black
I'd be curious to see the IL code of this and a String.Join(). I'd like to think they are the same.
Simucal
I am pretty certain they do something similar.
James Black
Yeah, it wouldn't surprise me if they compiled to the same thing. For someone coming across the code later though, String output = String.Join(" ", myStrings); would be easier to understand at a glance.
Damovisa