Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string to an array of strings without multiple spaces

I have string $x from a TextBox:
enter image description here

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": enter image description here

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

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:
enter image description here

How can I split a string to an array of strings separated by "*" ?

like image 962
E235 Avatar asked Jun 09 '26 23:06

E235


1 Answers

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"
like image 116
Mathias R. Jessen Avatar answered Jun 15 '26 17:06

Mathias R. Jessen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!