user5385978
user5385978

Reputation:

converting an array of strings into a simple string and vice-versa in c#

Lets say, Here is an array of strings in c#:

string[] array = new string[] { "one", "two", "three" };

Is there any way to convert this string array into a string like this:

 "one,two,three"

And after converting into this string, how will I get back the previous array of strings, I mean how will I convert the string into an array of strings again?

string[] array = new string[] { "one", "two", "three" };

Upvotes: 1

Views: 516

Answers (3)

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

join

var str = string.Join(",", array);

array

var strArr = str.Split(',');

DOTNETFIDDLE

Upvotes: 3

nozzleman
nozzleman

Reputation: 9649

Given your array of strings:

string[] array = new string[] { "one", "two", "three" };

You can join it like this (there are several other ways, but this is one of the simpler ones)

var str = string.Join(",", array);

see msdn and dotnetpearls for further information on this method which also has some interestiong overoads.

Then you can turn it back to an array using the split method ob your joined string like so:

var array2 = str.Split(',');

Also, see msdn or dotnetpearls for deeper knowledge on this method.

Upvotes: 2

Mohit S
Mohit S

Reputation: 14064

Your Asnwer is Join and Split will help you to do this

Join

The string.Join method combines many strings into one. It receives two arguments: an array or IEnumerable and a separator string. It places the separator between every element of the collection in the returned string.

string.Join(",", array)

Split

Often strings have delimiter characters in their data. Delimiters include "," the comma and "\t" tab characters.

string[] words = JoinedString.Split(',');

Upvotes: 2

Related Questions