Is there any way to convert a string ("abcdef") to an array of string containing its character (["a","b","c","d","e","f"]) without using the String.Split function?
5 Answers
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();
}
2 Comments
Francine DeGrood Taylor
Actually, although both of your examples will give you the same string array in the end, the second ("older") way is considerably faster. LINQ has to do a fair amount of overhead translation before breaking the code down to what is, essentially, the second set of code. Try a timing test; the LINQ takes more than twice as long as the "longhand" example.
jason
I suspect that there is something wrong with your method of timing.
Yes.
"abcdef".ToCharArray();
2 Comments
jason
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.G-Wiz
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.