我想拆分一个字符串,然后将结果修剪为一行。
所以字符串:
"psychology ¦ history ¦ geography"
应返回以下成员,不带尾随或前导空格:
psychology
history
geography
我已经尝试过:
String.Split("¦").Trim
但是 Trim
不适用于数组。是否有一种单行方法,无论多么肮脏,都可以完成这项工作?
我确信这已经被欺骗了很多次,但我找不到 VB.Net
的相关解决方案。请不要仅链接到其他语言的问题而不解释如何将解决方案转换为 VB.Net
。
最佳答案
您可以 Split
和 Trim
使用 LINQ 的 Select 将字符串放在一行中方法。
都将字符串分配给局部变量:
Dim input As String = "psychology ¦ history ¦ geography"
Dim result1 = input.Split("¦"c).Select((Function(s) s.Trim))
或者直接使用字符串作为源:
Dim result2 = "psychology ¦ history ¦ geography".Split("¦"c).Select((Function(s) s.Trim))
请注意 Type
的result1
和result2
现在是IEnumerable(Of String) ,不是数组:
LINQ 的方法返回 IEnumerable<T>
如果没有另外指示。
另请注意,此语法假设 Option Infer
是 On
。如果你保留它Off
,您需要显式声明类型:
Dim result As IEnumerable(Of String) = (...)
如果您需要字符串数组作为输出,您需要询问:
Dim result3 As String() = input.Split("¦"c).Select((Function(s) s.Trim)).ToArray()
关于附加到 c
的类型字符 ( Split
)方法参数:
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.
关于vb.net - 如何在一行中分割和修剪字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53742123/