Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET String Split()

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
like image 457
mcu Avatar asked Feb 21 '12 05:02

mcu


People also ask

How can I split a string in C#?

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.

What is split () function in string?

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.

How do I split a string into string?

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.


1 Answers

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).

like image 180
penartur Avatar answered Oct 04 '22 23:10

penartur