Reputation: 2509
I want to Split a string and then Trim the results in one single line.
So the string:
"psychology ¦ history ¦ geography"
should return the following members without trailing or leading spaces:
psychology
history
geography
I've tried:
String.Split("¦").Trim
but Trim
does not work for arrays. Is there a one-line method, no matter how dirty, that does this job?
I'm sure this has been duped many times but I couldn't find the relevant solution for VB.Net
. Please don't just link to a question in another language without explaining how I can convert the solution to VB.Net
.
Upvotes: 2
Views: 4107
Reputation: 2786
If you don't have embedded spaces in the items, you can just pass the space character as a separator as well as pipe. Combine that with the remove empty entries option and multiple space separators aren't an issue. If you need to handle other whitespace characters, you can add those.
input.Split(New String() {"|", " "}, StringSplitOptions.RemoveEmptyEntries)
Upvotes: 0
Reputation: 32278
You can Split
and Trim
your string in one line using the LINQ's Select method.
Both assigning the string to a local variable:
Dim input As String = "psychology ¦ history ¦ geography"
Dim result1 = input.Split("¦"c).Select((Function(s) s.Trim))
Or directly using the string as source:
Dim result2 = "psychology ¦ history ¦ geography".Split("¦"c).Select((Function(s) s.Trim))
Note that the Type
of result1
and result2
is now an IEnumerable(Of String), not an array:
LINQ's methods return a IEnumerable<T>
if not otherwise instructed.
Also note that this syntax supposes that Option Infer
is On
. If you keep it Off
, you need to declare the type explicitly:
Dim result As IEnumerable(Of String) = (...)
If you need a string Array as output, you need to ask:
Dim result3 As String() = input.Split("¦"c).Select((Function(s) s.Trim)).ToArray()
About the Type Characters (c
) appended to the Split
method parameter:
From the Visual Basic Language Reference: Char Data Type
Type Characters. Appending the literal type character
C
to a single-character string literal forces it to theChar
data type.Char
has no identifier type character.
Upvotes: 5