简体   繁体   中英

C# string.split variances

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM