Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to array in without using Split function

Tags:

arrays

string

c#

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?

like image 834
peanut Avatar asked Jan 08 '10 02:01

peanut


People also ask

Which function will use to convert from string to array?

The comma “,” is passed to the explode() function as a delimiter to convert the string into array elements.

How do I split a string into an array of strings?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 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();
}
like image 136
jason Avatar answered Oct 16 '22 09:10

jason


Yes.

"abcdef".ToCharArray();
like image 22
G-Wiz Avatar answered Oct 16 '22 09:10

G-Wiz