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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With