What's an efficient way to concatenate all strings in an array, separating with a space?
-
21-08-2019 - |
Question
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?
Solution
Try this:
String output = String.Join(" ", myStrings);
OTHER TIPS
StringBuilder buf = new StringBuilder();
foreach(var s in myStrings)
buf.Append(s).Append(" ");
var ss = buf.ToString().Trim();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow