Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string.split variances

Tags:

c#

I have probably missed something very basic but this has me stumped.

When using String.Split() I get different results between

.Split(' ')  

and

.Split(new char[' ']) 

Given this code:

using (System.IO.StreamWriter sw = new StreamWriter(@"C:\consoleapp1.log", true)) {     string anystring = "pagelength=60 pagewidth=170 cpi=16 lpi=8 landscape=1 lm=2";     sw.WriteLine(".Split(' ')");     string[] anystrings1 = anystring.Split(' ');     for (int i = 0; i < anystrings1.Length; i++)     {         sw.WriteLine($@"{i,2}: {anystrings1[i]}");     }     sw.WriteLine(".Split(new char[' '])");     string[] anystrings2 = anystring.Split(new char[' ']);     for (int i = 0; i < anystrings2.Length; i++)     {         sw.WriteLine($@"{i,2}: {anystrings2[i]}");     }  } 

Why do I get different results:

.Split(' ')  0: pagelength=60  1: pagewidth=170  2: cpi=16  3: lpi=8  4: landscape=1  5: lm=2 .Split(new char[' '])  0: pagelength=60 pagewidth=170 cpi=16 lpi=8 landscape=1 lm=2 
like image 803
John Avatar asked Jul 14 '17 12:07

John


1 Answers

new char[' '] 

does not do what you think it does.

Space is ASCII character 32 (and C# allows implicit conversions between char and int). So that code creates an array of char with size of 32.

like image 58
mjwills Avatar answered Sep 25 '22 23:09

mjwills