I have string $x from a TextBox:

I want to split this string to an array of strings without the '*'.
I run: $a = $x.Split("*") but I received double spaces in the "7-zip":

Suggestion 1:
Here they suggested to user -split but when using it I received a string (array of chars), not an array of strings:

Suggestion 2:
In this blog and on this question they suggested to use [System.StringSplitOptions]::RemoveEmptyEntrie + foreach (in the blog) in order to parse the un-wanted spaces.
I tried:
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$b = $x.Split("*", $option) |foreach {
$_.Split(" ", $option)
}
But it didn't help:

How can I split a string to an array of strings separated by "*" ?
As you've found out, you can remove the "blank" entry after the last occurrence of * with [StringSplitOptions]::RemoveEmptyEntries.
Now, all you need to do to remove unwanted space around the words, is to call Trim():
$x = @"
ccleaner*
7-zip*
"@
$Words = $x.Split('*',[StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object {
$_.Trim()
}
PS C:\> $Words[0]
ccleaner
PS C:\> $Words[0]
7-zip
PS C:\>
You can also use -split (you only need a single \ to escape *) and then filter out empty entries with Where-Object:
"a*b* *c" -split "\*" | Where-Object { $_ -notmatch "^\s+$" }| ForEach-Object { $_.Trim() }
or the other way around (use Where-Object after removing whitespace):
"a*b* *c" -split "\*" | ForEach-Object { $_.Trim() } | Where-Object { $_ }
You could also use -replace to remove leading and trailing whitespace (basically, the regex version of Trim()):
" a b " -replace "^\s+|\s+$",""
# results in "a b"
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