views:

69

answers:

4

When this is valid:

string s4 = "H e l l o";

string[] arr = s4.Split(new char[] { ' ' });        
foreach (string c in arr)
{
    System.Console.Write(c);  
}

Why This is invalid

string s4 = "H e l l o";

char[] arr = s4.Split(new char[] { ' ' });        
foreach (char c in arr)
{
    System.Console.Write(c);  
}

Cant We build a Character Array with Splitter method.

+4  A: 

char is not a subtype of string, to start with. So, because string.Split returns an array of strings, it's not an array of char, even if every string is of length 1.

ammoQ
+1  A: 

Why This is invalid

Because Split returns string[] and not char[]

Cant We build a Character Array with Splitter method.

Refer to Thomas' answer (using linq)

Thanks

Mahesh Velaga
+2  A: 

Split method returns string[], not char[]. even if the length of each string is 1.

You can use String.toCharArray() if you'd like.

Sagi
+5  A: 

Your intention by saying

char[] arr = s4.Split(new char[] { ' ' });

is to tell the compiler much more than he knows, that the parts after the split will be each one character long and you want to convert them to char. Why don't you tell him explicitly, e.g. by saying

char[] arr = s4.Split(new char[] { ' ' }).Select(c => c[0]).ToArray();

Thomas Wanner
+1, but I'd also point out that it's `Split(params char[])` so you can just say `s4.Split(' ').Select(c=> c[0]).ToArray()`
Isaac Cambron
So using LINQ we can explicitly guide compiler, That's nice.
Nani