1

A spin-off question from another SO question.

When splitting a here-string on carridge return + line feed [backtick]r[backtick]n I would expect the following results

$theString = @"
word
word
word
word
word
"@

$theString.Split("`r`n") | Measure-Object

Count    : 5
Average  : 
Sum      : 
Maximum  : 
Minimum  : 
Property : 

Instead what I get is the following output

Count    : 9
Average  : 
Sum      : 
Maximum  : 
Minimum  : 
Property : 

The extra 4 object are empty strings. Running %{ $_.GetType().FullName} shows all items of type System.String. In the aforementioned SO Question the answers account for the empty strings. I am trying to understand why they are created from the split when I wouldnt expect them to be.

2 Answers 2

2

String.Split() splits on any of the characters specified in the match pattern, and because `r`n is two characters, you're getting:

word`r    
`n    
word`r    
`n

Instead of specifying characters directly in your code, use the .NET System.Environment enumeration's NewLine member. Then use System.StringSplitOptions to remove any empty entries.

$theString.Split([System.Environment]::NewLine, [System.StringSplitOptions]::RemoveEmptyEntries) |
    measure-object
Sign up to request clarification or add additional context in comments.

Comments

2

I usually recommend @alroc 's solution. An alternative way is to use the -split operator.

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 : 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.