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"
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.
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.
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 .
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.
A simple one...
string[] theArray = new string[]{"Apples", "Bananas", "Cherries"}; string s = string.Join(",",theArray);
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...)
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