Reputation: 985
I am little bit confuse in Split function in Vb.Net.
If hdnDetails.Value.Split("|").Length = 0 Then
lblMsg.Text="Error"
End If
This statement is always true even hdnDetails.Value=""
. Split function returning length 1 always. What is the solution to get 0 length?
Upvotes: 1
Views: 971
Reputation: 460380
String.Split
will never return an array with Length = 0
(with this overload). MSDN:
If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.
So you should use String.Contains
if you want to check if the string contains a char:
If Not hdnDetails.Value.Contains("|") Then
lblMsg.Text="Error"
Else
Dim array = hdnDetails.Value.Split("|")
' Do something with this array if you need it
End If
You should note that checking if the array length is 1 can also be wrong if you want to know whether the string contained the separator or not. The array length can even be 0 if you use the String.Split
overload that takes a StringSplitOptions
argument.
Consider the string contains only the separator so it's "|"
and you pass StringSplitOptions.RemoveEmptyEntries
, then the resulting array will have a length of 0.
If you pass StringSplitOptions.None
you will get an array with length of 2: two empty strings.
Upvotes: 3