Split("", "|") returns 1 项
Split("", "|") returns 1 item
当我执行以下操作时......
Dim s As String = ""
Dim sLines() As String = s.Split("|", StringSplitOptions.None)
...
sLines.Count 是 1.
为什么?
没有什么要拆分的,要拆分的字符串是空的,所以我希望sLines.Count为0。
谢谢。
查看 Split
的文档:
If this instance does not contain any of the strings in separator, the returned array consists of a single element that contains this instance.
这就是你的情况。 ""
不包含 "|"
,因此返回单个元素 ""
。
一种一致性:如果 "a|b"
在 |
上拆分是 ["a"
、"b"
] 并且 "a"
在 |
上拆分是 ["a"
],"|b"
在 |
上拆分为 [""
、"b"
] 和 ""
在 |
变为 [""
].
您可以通过传递 StringSplitOptions.RemoveEmptyEntries
而不是 None
来删除 所有 个空条目,否则只需手动检查 s = String.Empty
。
可以使用IIf()
函数来处理空字符串
Dim s As String = ""
Dim sLines() As String = IIf(s = String.Empty, Nothing, s.Split("|"))
Dim cnt As Integer
If sLines IsNot Nothing Then
'your code
cnt = sLines.Count
Else
'your code
cnt = 0
End If
注意: 如果你想处理空格(Dim s As String = " "
),只需像这样使用 trim()
IIf(Trim(s) = String.Empty, Nothing, s.Split("|"))
当我执行以下操作时......
Dim s As String = ""
Dim sLines() As String = s.Split("|", StringSplitOptions.None)
...
sLines.Count 是 1.
为什么?
没有什么要拆分的,要拆分的字符串是空的,所以我希望sLines.Count为0。
谢谢。
查看 Split
的文档:
If this instance does not contain any of the strings in separator, the returned array consists of a single element that contains this instance.
这就是你的情况。 ""
不包含 "|"
,因此返回单个元素 ""
。
一种一致性:如果 "a|b"
在 |
上拆分是 ["a"
、"b"
] 并且 "a"
在 |
上拆分是 ["a"
],"|b"
在 |
上拆分为 [""
、"b"
] 和 ""
在 |
变为 [""
].
您可以通过传递 StringSplitOptions.RemoveEmptyEntries
而不是 None
来删除 所有 个空条目,否则只需手动检查 s = String.Empty
。
可以使用IIf()
函数来处理空字符串
Dim s As String = ""
Dim sLines() As String = IIf(s = String.Empty, Nothing, s.Split("|"))
Dim cnt As Integer
If sLines IsNot Nothing Then
'your code
cnt = sLines.Count
Else
'your code
cnt = 0
End If
注意: 如果你想处理空格(Dim s As String = " "
),只需像这样使用 trim()
IIf(Trim(s) = String.Empty, Nothing, s.Split("|"))