views:

374

answers:

4

is there any way to convert a string like "abcdef“ to string array a char each without using the string.split function?

Thanks first

+2  A: 

Yes.

"abcdef".ToCharArray();
gWiz
He said `string` array, not `char` array. Note that if you could `String.Split` on the empty `char` between each `char` in the `string` the result would be a `string[]`. This seems to be the behavior he is seeking.
Jason
My bad. I took liberties trying to interpret the improper grammar of his question, but my interpretation was clearly wrong. Thanks for pointing it out.
gWiz
+5  A: 

So you want an array of string, one char each:

string s = "abcdef";
string[] a = s.Select(c => c.ToString()).ToArray();

This works because string implements IEnumerable<char>. So Select(c => c.ToString()) projects each char in the string to a string representing that char and ToArray enumerates the projection and converts the result to an array of string.

If you're using an older version of C#:

string s = "abcdef";
string[] a = new string[s.Length];
for(int i = 0; i < s.Length; i++) {
    a[i] = s[i].ToString();
}
Jason
+1  A: 

You could use linq and do:

string value = "abcdef";
string[] letters = value.Select(c => c.ToString()).ToArray();

This would get you an array of strings instead of an array of chars.

Adam Gritt
A: 

Bit more bulk than those above but i don't see any simple one liner for this.

List<string> results = new List<string>; 

foreach(Char c in "abcdef".ToCharArray())
{
   results.add(c.ToString());
}


results.ToArray();  <-- done

What's wrong with string.split???

Wardy