VB.NET missing isNull()? - vb.net

I like to confirm that array is created, how can it be done? There is no nul keyword?
Dim items As Array = str.Split("|")
if (items=null) then ???

To check if an object is null in VB.Net you need to use the Nothing keyword. e.g.
If (items is Nothing) Then
'do stuff
End If
However string.Split() never returns null, so you should check the input string for null rather than the items array. Your code could be changed to something like:
If Not String.IsNullOrEmpty(str) Then
Dim items As Array = str.Split("|")
'do stuff
End If

Try using String.IsNullOrEmpty on your string variable before splitting it. If you attempt to split the variable with nothing in the string the array will still have one item in it (an empty string), therefore your IsNothing checks on the array will return false.

String.Split can never return null. At worst, it can return an array with no elements.

Use "Is Nothing" to test for Null in VB.NET.
If items Is Nothing Then
End If

The keyword for null in VB is Nothing.
However, this is not what you want to use in this case. The Split method never returns a null reference. It always returns a string array that has at least one item. If the string that you split was empty, you get an array containing one string with the length zero.
So, to check if you get that as result you would do:
Dim items As String() = str.Split("|")
If items.Length = 1 and items(0).Length = 0 Then ...
It's of course easier to check the input first:
If str.Length = 0 Then ...

For a one liner do this:
destinationVariable = if(myvar is nothing, "", myvar)

Related

Comparing strings in a loop using Is Operator

Is Operator works fine when comparing two strings like:
Dim str1 As String = "TagnameX"
Dim str2 As String = "TagnameX"
Dim strChk as boolean = str1 Is str2
'strChk returns True
But when one of the strings is extracted by Substring it returns false ! as below:
Dim str1 As String = "t#1TagnameX"
Dim str1Extract As String = str1.Substring(3, 8)
Dim strArr() = {"Tagname1", "Tagname2", "TagnameX"}
For i = 0 To strArr.Length - 1
If strArr(i) Is str1Extract Then
MsgBox("TagnameX found!")
else
MsgBox("TagnameX was not found!")
End If
Next
'TagnameX was not found!
so am i using it wrong in some how? thanks for your help! :)
The Is-operator returns whether two references are equal: that is, whether the two variables refer to the same location in memory.
The first code snippet returns True because for literal strings, .NET interns duplicates rather than keeping separate identical copies in memory, so str1 and str2 refer to the same string in memory.
The second code snippet returns False because .NET does not necessarily intern intermediate strings, such as strings returned by Substring. So the variables str and strExtract do not refer to the same string.
You should use the equals operator = to compare the value of two strings.
I don't think that the Is operator does what you think it does.
The Is operator determines if two object references refer to the same object. However, it does not perform value comparisons.
https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/is-operator
Instead just use = to compare string values.
If strArr(i) = str1Extract Then

Visual Basic .NET Empty/Null String difference?

I would like to differentiate between NULL and "".
How do I determine with an if statement if a String is NULL or ""?
Nothing is when the string variable has no instance it refers to at all while "" is when the string variable has something it refers to and it is an empty string.
To distinguish, you could put the following conditions:
Dim s As String
If s Is Nothing Then 'It means it is Nothing
End If
If s = "" Then 'It means it points to some instance whose value is empty string
End If
VB.Net also has String.Empty which is equivalent to "":
If s = String.Empty Then
End If
"" is just an empty string, but it is still initialized and has an allocated position in the memory as a string with no characters.
Null or Nothing is a string that has not been initialized or defined, which means that there is no memory is allocated for this, thus the string technically doesn't exist.
To check if a string is null you'd do:
If str Is Nothing Then
To check if a string is empty you could do:
If str = "" Then
or:
If str.Length = 0 Then
However, to check if it's either null or empty, you get use of the String.IsNullOrEmpty() method:
If String.IsNullOrEmpty(str) Then
you can get dbnulll error if string come from database
you can determine it with
isdbnull(str)
Pass your string variable into this function to test for both:
String.IsNullOrEmpty(s)
You can test for null like this:
s Is Nothing
You can test if it is an empty string like this:
s = String.Empty
The accepted answer and the others are all partially wrong because they do not address a crucial point of empty strings in VB. According to the documentation:
For strings in Visual Basic, the empty string equals Nothing. Therefore, "" = Nothing is true.
This means that MyString = String.Empty will be true when MyString Is Nothing is also true. So you definitely want to test against Nothing before testing against String.Empty (or "").

VB.Net Extract numbers from string function

My request is one that can extract a number somewhat by a search.
Example:
animalsOwned|4 would return an containing "4"
animals|3|2|1|3 would return an array containing "3", "2", "1", "3"
This would make it easier for me during a file stream reader.
Thank you
Dim astring = "ABCDE|1|2|3|4"
Dim numbers = (From s In astring
Where Char.IsDigit(s)
Select Int32.Parse(s)).ToArray()
This LINQ statement should help. It simply checks each character in a string to see if it's a digit. Note that this only applies to single digit numbers. It becomes a bit more complicated if you want "ABC123" to return 123 vs. 1, 2, 3 array.
Try regular expression. It's a powerful tool for simple text parsing.
Imports System.Text.RegularExpressions
Namespace Demo
Class Program
Shared Function Main(ByVal args As String()) As Integer
Dim array As Integer() = ExtractIntegers("animals|3|2|1|3")
For Each i In array
Console.WriteLine(i)
Next
Return 0
End Function
Shared Function ExtractIntegers(ByVal input As String) As Integer()
Dim pattern As String = "animals(\|(?<number>[0-9]+))*"
Dim match As Match = Regex.Match(input, pattern)
Dim list As New List(Of Integer)
If match.Success Then
For Each capture As Capture In match.Groups("number").Captures
list.Add(Integer.Parse(capture.Value))
Next
End If
Return list.ToArray()
End Function
End Class
End Namespace
I haven't programmed VB for awhile but I'll give you some pseudo code:
First, loop through each line of file. Call this variable Line.
Then, take the index of what you're searching for: like Line.indexOf("animalsOwned")
If it returns -1 it isn't there; continue.
Once you find it, add the Index variable to the length of the search string and 1. (Index=Index+1+Len(searchString))
Then, take a substring starting there, and end at the end of the line.
Explode the substring by | characters, then add each into an array.
Return the array.
Sorry that I can't give you much help, but I'm working on an important PHP website right now ;).
You can do a variable.Split("|") and then assign each piece to an array level.
You can do a count on string and with a while or for loop, you can assign the splited sections to array levels. Then you can do a IsNumeric() check for each array level.

splitting a string in VB

I have a ComboBox which I assign to a variable:
Dim var as String = ComboBox1.SelectedValue
Dim name As String = var.Split(",")
This gives me the error
Value of type '1-dimensional array of string' cannot be converted to String
Any ideas as to where I'm going wrong?
Split returns an array of strings. Your variable needs to be changed to an array, not just a single string.
My VB is a bit rusty, but I think you have to make name an array:
Dim name() As String = var.Split(",")
name needs to be declared as an array.
dim name() as string = var.split(",")
The split() method will break up the string based on the given character and put each newly created string into an array and return it.
This is what your error message is telling you:
Value of type '1-dimensional array of string' cannot be converted to String
The method returns an array of string, but your trying to put it into just a string!
EDIT: In response to your answer...
So far you've managed to split the string yourself with the split method. To output this to your message box, you need to concatenate the two elements in the proper order:
msgbox(name(1) & " " & name(0))
Notice I indexed the array twice! Element 1 is the first name, element 0 is the last name. Remember you got this name in lname,fname format. Passing the array itself doesn't make sense! Remember, a datatype is not equal to an array of that type, they are two different things. Therefore a string is not compatible with a string array. However, each individual element of the array is a string, and so each of those are compatible with the string type (because they're the same thing)!
Dim var As String = ComboBox1.SelectedValue
Dim temp() As String = Split(var, ",", -1, CompareMethod.Binary)
Dim name As String = temp(0)
Or maybe "name" isn't an array and the goal is to populate "name" with everything up until the first comma, in which case the fix would be:
Dim name as String = var.Split(",")(0)
Note: assumes that var is not Nothing.

If Not String.Empty ignoring empty string - VB.NET

I have a array of strings and I am looping through them, but the string might be empty so I am trying this:
For Each Component As String In Components
If Component IsNot String.Empty Then
'Work your magic
End If
Next
But if Component is an empty string the logic still fires. I've also tried
If Component <> "" Then
End If
With the same results. So what am I missing?
Make sure that your List is of type string
Use the String.IsNullOrEmpty method.
Sub Main
Dim foo As String
foo = "Non-Empty string"
If Not String.IsNullOrEmpty(foo) Then
Console.WriteLine("Foo is not empty.")
End If
End Sub
One thing that has gotten me before is spaces. You can't see it when you view the variable in the watch window, but it makes the string not empty or null.
Do your string have default values and are they actually ""? What if you used:
If Not Component Is Nothing Then
End If