How to convert string to string[]?
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
.
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 };
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()
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