使用不带参数的Split和RemoveEmptyEntries选项之间的区别

see*_*uit 10 c# split removing-whitespace

我正在检查给定文本文件中的行.行可能有随机空格,我只对检查行中的单词数而不是空格感兴趣.我做:

string[] arrParts = strLine.Trim().Split();

if (arrParts.Length > 0)
{ 
    ...
}
Run Code Online (Sandbox Code Playgroud)

现在,根据msdn,

If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.
Run Code Online (Sandbox Code Playgroud)

IsWhiteSpace方法涵盖了许多不同形式的空白,包括通常:' ' \t and \n

不过最近我见过这种格式:

Split(new char[0], StringSplitOptions.RemoveEmptyEntries)

这有什么不同?

mus*_*fan 6

请考虑以下字符串:

"Some  Words"//notice the double space
Run Code Online (Sandbox Code Playgroud)

使用Split()将分割在空白区域,并且由于双倍空间将包括3个项目("Some","","Words").

StringSplitOptions.RemoveEmptyEntries选项指示函数对Emtpy条目进行折扣,因此会产生2个项目("Some","Words")

这是一个有效的例子


为完整new char[0]起见,提供参数以访问允许指定的重载StringSplitOptions.要使用默认分隔符,separator参数必须null为零长度.但是,在这种情况下,使用null将满足多个重载,因此您必须指定有效类型(char[]或者string[]).这是可以做到多种方式,如(char[])nullnull as char[],或通过使用一个零长度字符数组像上面.

浏览此处获取更多信息