Advertisement
Advertisement


How to convert string to string[]?


Question

How to convert string type to string[] type in C#?

2012/06/18
1
64
6/18/2012 1:01:19 PM

Accepted Answer

string[] is an array (vector) of strings string is just a string (a list/array of characters)

Depending on how you want to convert this, the canonical answer could be:

string[] -> string

return String.Join(" ", myStringArray);

string -> string[]

return new []{ myString };
2012/06/18
113
6/18/2012 11:11:29 AM

An array is a fixed collection of same-type data that are stored contiguously and that are accessible by an index (zero based).

A string is a sequence of characters.

Hence a String[] is a collection of Strings.

For example:

String foo = "Foo";  // one instance of String
String[] foos = new String[] { "Foo1", "Foo2", "Foo3" };
String firstFoo = foos[0];  // "Foo1"

Arrays (C# Programming Guide)

Edit: So obviously there's no direct way to convert a single String to an String[] or vice-versa. Though you can use String.Split to get a String[] from a String by using a separator(for example comma).

To "convert" a String[] to a String(the opposite) you can use String.Join. You need to specify how you want to join those strings(f.e. with comma).

Here's an example:

var foos = "Foo1,Foo2,Foo3";
var fooArray = foos.Split(',');  // now you have an array of 3 strings
foos = String.Join(",", fooArray); // now you have the same as in the first line
2012/06/18

If you want to convert a string like "Mohammad" to String[] that contains all characters as String, this may help you:

"Mohammad".ToCharArray().Select(c => c.ToString()).ToArray()

You can create a string[] (string array) that contains your string like :

string someString = "something";
string[] stringArray = new string[]{ someString };

The variable stringArray will now have a length of 1 and contain someString.


To convert a string with comma separated values to a string array use Split:

string strOne = "One,Two,Three,Four";
string[] strArrayOne = new string[] {""};
//somewhere in your code
strArrayOne = strOne.Split(',');

Result will be a string array with four strings:

{"One","Two","Three","Four"}

2017/07/26

string is a string, and string[] is an array of strings

2012/06/18