41

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"

4 Answers 4

79

A simple one...

string[] theArray = new string[]{"Apples", "Bananas", "Cherries"};
string s = string.Join(",",theArray);
Sign up to request clarification or add additional context in comments.

5 Comments

Hey, I knew that really. It's just very hot in the office today and I haven't had a coffee! Thanks.
Although it feels a bit odd. It think it is more an action on an array than an action on a string so it would be more "natural" for me to look for such a function in the array class. But thanks, I did not know there was such a way to join a string[] (so no more for constructions)! +1
But it would only apply to string[], not to any others - so it doesn't fit cleanly into the "regular" array implementation. But you could add it as a C# 3.0 extension method to this string[].
Why should you only be able to use string[] and not any type of array. I think it would be possible to just use the ToString() method of the objects in the array (at least I would do it that way) so you can also Join arrays of integers, longs and even complex objects (even your own objects when implementing the ToString). I don't know how other languages solve this, but because it was not in the array class I never noticed it (and creating a for was quicker than doing research on the internet).
Then write a Join<T>(this T[] array) extension method ;-p
12

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...)

Comments

9

String.Join Method (String, String[])

Comments

1

You can use Aggregate, it applies an accumulator function over a sequence.

string[] test = new string[]{"Apples", "Bananas", "Cherries"};
char delemeter = ',';
string joinedString = test.Aggregate((prev, current) => prev + delemeter + current);

Comments

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.