String 在此处拆分字符串时为空字符串
另一个SO的衍生问题 在carridge return+换行符[backtick]r[backtick]n上拆分here字符串时,我希望得到以下结果String 在此处拆分字符串时为空字符串,string,powershell,powershell-3.0,String,Powershell,Powershell 3.0,另一个SO的衍生问题 在carridge return+换行符[backtick]r[backtick]n上拆分here字符串时,我希望得到以下结果 $theString = @" word word word word word "@ $theString.Split("`r`n") | Measure-Object Count : 5 Average : Sum : Maximum : Minimum : Property : 相反,我得到的是以下输出
$theString = @"
word
word
word
word
word
"@
$theString.Split("`r`n") | Measure-Object
Count : 5
Average :
Sum :
Maximum :
Minimum :
Property :
相反,我得到的是以下输出
Count : 9
Average :
Sum :
Maximum :
Minimum :
Property :
额外的4个对象是空字符串。运行%{$\u.GetType().FullName}
将显示System.String
类型的所有项。在前面提到的SO问题中,答案解释了空字符串。我正在试图理解为什么它们是在我不希望的情况下从拆分中创建的。String.split()
对匹配模式中指定的任何字符进行拆分,因为'r`n是两个字符,所以您得到:
word`r
`n
word`r
`n
不要直接在代码中指定字符,而是使用.NET。然后使用删除所有空条目
$theString.Split([System.Environment]::NewLine, [System.StringSplitOptions]::RemoveEmptyEntries) |
measure-object
String.Split()
对匹配模式中指定的任何字符进行拆分,因为'r`n是两个字符,所以您得到:
word`r
`n
word`r
`n
不要直接在代码中指定字符,而是使用.NET。然后使用删除所有空条目
$theString.Split([System.Environment]::NewLine, [System.StringSplitOptions]::RemoveEmptyEntries) |
measure-object
我通常推荐@alroc的解决方案。另一种方法是使用
-split
运算符
PS P:\> $theString = @"
word
word
word
word
word
"@
$theString -split "`r`n" | Measure-Object
$theString -split [environment]::NewLine | Measure-Object
Count : 5
Average :
Sum :
Maximum :
Minimum :
Property :
Count : 5
Average :
Sum :
Maximum :
Minimum :
Property :
我通常推荐@alroc的解决方案。另一种方法是使用
-split
运算符
PS P:\> $theString = @"
word
word
word
word
word
"@
$theString -split "`r`n" | Measure-Object
$theString -split [environment]::NewLine | Measure-Object
Count : 5
Average :
Sum :
Maximum :
Minimum :
Property :
Count : 5
Average :
Sum :
Maximum :
Minimum :
Property :