开发者

String to Arrays conversion

开发者 https://www.devze.com 2022-12-21 03:19 出处:网络
When this is valid: string s4 = \"H e l l o\"; string[] arr = s4.Split(new char[] { \' \' }); foreach (string c in arr)

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

C开发者_运维知识库ant We build a Character Array with Splitter method.


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


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.


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

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消