The Kirkland Coder: My Delimiters

Tuesday, February 21, 2012

My Delimiters

When I split a string, I prefer to use a character array for my delimiters. It is handy when you have users that tend to use several different types, and not always consistently. But you should be warned that it might need to be edited when using it with CSV files. So here is the declaration I use:

[char[]]$Delimiters = @(';', ',', "`t")

So this works well with the "Split" command. For example:

[char[]]$Delimiters = @(';', ',', "`t")
[string]$String = "One,Two;Three"
[array]$NewArray = $String.Split($Delimiters, [StringSplitOptions]'RemoveEmptyEntries')
Write-Host "The String:"
$String
Write-Host "The New Array:"
$NewArray

Would produce the following output:

The String:
One,Two;Three
The New Array:
One
Two
Three

No comments:

Post a Comment