Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's an efficient way to concatenate all strings in an array, separating with a space?

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?

like image 692
Damovisa Avatar asked May 12 '09 00:05

Damovisa


People also ask

What is the most efficient way to concatenate many strings together?

Concatenate Many Strings using the Join As shown above, using the join() method is more efficient when there are many strings. It takes less time for execution.

How do you concatenate strings in an array?

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

What is the correct way to concatenate the strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.


2 Answers

Try this:

String output = String.Join(" ", myStrings);
like image 91
Andrew Hare Avatar answered Sep 28 '22 12:09

Andrew Hare


StringBuilder buf = new StringBuilder();
foreach(var s in myStrings)
  buf.Append(s).Append(" ");
var ss = buf.ToString().Trim();
like image 27
James Black Avatar answered Sep 28 '22 12:09

James Black