.NET String Split()

Posted on

Problem :

It seems that the PowerShell -split operator and .NET Split() method act completely different.

.NET treats separator strings as if they were character arrays.

$str = "123456789"
Write-Host ".NET Split(): "
$lines = $str.Split("46")
Write-Host "Count: $($lines.Length)"

$str = "123456789"
Write-Host "-split operator: "
$lines = $str -split "46"
Write-Host "Count: $($lines.Length)"


.NET Split():
Count: 3

-split operator:
Count: 1

Is there a way to make a .NET application use the same technique as the PowerShell, and use the string separator as one solid unit? Hopefully, without RegEx.

This worked in PowerShell, using the Split():

Write-Host "Divided by 46:"
"123456789".Split([string[]]  "46", [StringSplitOptions]::None)

Write-Host "`n`nDivided by 45:"
"123456789".Split([string[]]  "45", [StringSplitOptions]::None)

Divided by 46:

Divided by 45:

Solution :


When you’re calling string.Split(string), it uses the string.Split(char[]) overload (as string could be casted to a char[], but not to string[]).

In order to use string.Split(string[], StringSplitOptions) overload, you must call it in a way "123456789".Split(new[] { "45" }, StringSplitOptions.None).

.NET’s String.Split method has two (groups of) overloads. The first receives a character array, and the second a string array. There isn’t actually an overload that receives a string. The first one behaves like you describe, with each character being split individually. The second splits along whole strings, like you want it to.

Due to the way PowerShell parses the parameters, a string passed to Split will be parsed as a char array, and the first overload called. If you could explicitly specify that the “46” is an array containing just one string, it should give you the behavior you want.

The key difference is that the -split operator can take a string or a regex pattern, while the Split method can only take strings. The -split operator has a lot of options to tweak its behavior. You can find more information in the about_split document

One other difference I did not see anyone mention is that the string .split() method only works on the single string object you’re calling the method on.

The PowerShell -split operator will take an array as its argument, and split all of the elements of the array at once.

Leave a Reply

Your email address will not be published. Required fields are marked *