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?
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.
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.
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.
Try this:
String output = String.Join(" ", myStrings);
StringBuilder buf = new StringBuilder();
foreach(var s in myStrings)
buf.Append(s).Append(" ");
var ss = buf.ToString().Trim();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With