Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string array to a concatenated string in C#

Tags:

arrays

string

c#

Is there an easy way to convert a string array into a concatenated string?

For example, I have a string array:

new string[]{"Apples", "Bananas", "Cherries"}; 

And I want to get a single string:

"Apples,Bananas,Cherries" 

Or "Apples&Bananas&Cherries" or "Apples\Bananas\Cherries"

like image 957
Oundless Avatar asked Aug 20 '09 09:08

Oundless


People also ask

How do you concatenate strings in C?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.

How do you concatenate 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.

Can you use += for string concatenation?

The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b .

How do I concatenate a char to a string in C++?

C++ has a built-in method to concatenate strings. The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function.


2 Answers

A simple one...

string[] theArray = new string[]{"Apples", "Bananas", "Cherries"}; string s = string.Join(",",theArray); 
like image 181
Marc Gravell Avatar answered Oct 14 '22 19:10

Marc Gravell


The obvious choise is of course the String.Join method.

Here's a LINQy alternative:

string.Concat(fruit.Select((s, i) => (i == 0 ? "" : ",") + s).ToArray()) 

(Not really useful as it stands as it does the same as the Join method, but maybe for expanding where the method can't go, like alternating separators...)

like image 33
Guffa Avatar answered Oct 14 '22 21:10

Guffa