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)"
$lines
$str = "123456789"
Write-Host "-split operator: "
$lines = $str -split "46"
Write-Host "Count: $($lines.Length)"
$lines
Output:
.NET Split():
Count: 3
123
5
789
-split operator:
Count: 1
123456789
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:
123456789
Divided by 45:
123
6789
Split(char[]) Method This method is used to splits a string into substrings that are based on the characters in an array. Syntax: public String[] Split(char[] separator); Here, separator is a character array that delimits the substrings in this string, an empty array that contains no delimiters, or null.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With