8

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?

2 Answers 2

29

Try this:

String output = String.Join(" ", myStrings);
Sign up to request clarification or add additional context in comments.

Comments

1
StringBuilder buf = new StringBuilder();
foreach(var s in myStrings)
  buf.Append(s).Append(" ");
var ss = buf.ToString().Trim();

3 Comments

I'd be curious to see the IL code of this and a String.Join(). I'd like to think they are the same.
I am pretty certain they do something similar.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.