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)
这有什么不同?
请考虑以下字符串:
"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[])null
或null as char[]
,或通过使用一个零长度字符数组像上面.
归档时间: |
|
查看次数: |
2189 次 |
最近记录: |