0

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 Answers 4

5

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();

Sign up to request clarification or add additional context in comments.

2 Comments

+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()
So using LINQ we can explicitly guide compiler, That's nice.
4

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.

Comments

2

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

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.