If Not String.Empty ignoring empty string - VB.NET - 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

Related

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 - If string contains "value1" or "value2"

I'm wondering how I can check if a string contains either "value1" or "value2"?
I tried this:
If strMyString.Contains("Something") Then
End if
This works, but this doesn't:
If strMyString.Contains("Something") or ("Something2") Then
End if
This gives me the error that conversion from string to Long can't be done.
If I put the or ("Something2") inside the parenthesis of the first one, it gives me the error that the string cannot be converted to Boolean.
So how can I check if the string contains either "string1" or "string2" without having to write too much code?
You have to do it like this:
If strMyString.Contains("Something") OrElse strMyString.Contains("Something2") Then
'[Put Code Here]
End if
You need this
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
'Code
End if
In addition to the answers already given it will be quicker if you use OrElse instead of Or because the second test is short circuited. This is especially true if you know that one string is more likely than the other in which case place this first:
If strMyString.Contains("Most Likely To Find") OrElse strMyString.Contains("Less Likely to Find") Then
'Code
End if
Here is the alternative solution to check whether a particular string contains some predefined string. It uses IndexOf Function:
'this is your string
Dim strMyString As String = "aaSomethingbb"
'if your string contains these strings
Dim TargetString1 As String = "Something"
Dim TargetString2 As String = "Something2"
If strMyString.IndexOf(TargetString1) <> -1 Or strMyString.IndexOf(TargetString2) <> -1 Then
End If
NOTE: This solution has been tested with Visual Studio 2010.
You have ("Something2") by itself - you need to test it so a boolean is returned:
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
End if
The error indicates that the compiler thinks you want to do a bitwise OR on a Boolean and a string. Which of course won't work.
If strMyString.Tostring.Contains("Something") or strMyString.Tostring.Contains("Something2") Then
End if
I've approached this in a different way. I've created a function which simply returns true or false..
Usage:
If FieldContains("A;B;C",MyFieldVariable,True|False) then
.. Do Something
End If
Public Function FieldContains(Searchfor As String, SearchField As String, AllowNulls As Boolean) As Boolean
If AllowNulls And Len(SearchField) = 0 Then Return True
For Each strSearchFor As String In Searchfor.Split(";")
If UCase(SearchField) = UCase(strSearchFor) Then
Return True
End If
Next
Return False
End Function
If you want to disregard whether the text is uppercase or lowercase, use this:
If strMyString.ToUpper.Contains("TEXT1") OrElse strMyString.ToUpper.Contains("TEXT2") Then
'Something
End if
Interestingly, this solution can break, but a workaround:
Looking for my database called KeyWorks.accdb which must exist:
Run this:
Dim strDataPath As String = GetSetting("KeyWorks", "dataPath", "01", "") 'get from registry
If Not strDataPath.Contains("KeyWorks.accdb") Then....etc.
If my database is named KeyWorksBB.accdb, the If statement will find this acceptable and exit the If statement because it did indeed find KeyWorks and accdb.
If I surround the If statement qualifier with single quotes like 'KeyWorks.accdb', it now looks for all the consecutive characters in order and would enter the If block because it did not match.

split string error in a compiled VB.NET class

I'm having some trouble compiling some VB code I wrote to split a string based on a set of predefined delimeters (comma, semicolon, colon, etc). I have successfully written some code that can be loaded inside a custom VB component (I place this code inside a VB.NET component in a plug-in called Grasshopper) and everything works fine. For instance, let's say my incoming string is "123,456". When I feed this string into the VB code I wrote, I get a new list where the first value is "123" and the second value is "456".
However, I have been trying to compile this code into it's own class so I can load it inside Grasshopper separately from the standard VB component. When I try to compile this code, it isn't separating the string into a new list with two values. Instead, I get a message that says "System.String []". Do you guys see anything wrong in my compile code? You can find an screenshot image of my problem at the following link: click to see image
This is the VB code for the compiled class:
Public Class SplitString
Inherits GH_Component
Public Sub New()
MyBase.New("Split String", "Split", "Splits a string based on delimeters", "FireFly", "Serial")
End Sub
Public Overrides ReadOnly Property ComponentGuid() As System.Guid
Get
Return New Guid("3205caae-03a8-409d-8778-6b0f8971df52")
End Get
End Property
Protected Overrides ReadOnly Property Internal_Icon_24x24() As System.Drawing.Bitmap
Get
Return My.Resources.icon_splitstring
End Get
End Property
Protected Overrides Sub RegisterInputParams(ByVal pManager As Grasshopper.Kernel.GH_Component.GH_InputParamManager)
pManager.Register_StringParam("String", "S", "Incoming string separated by a delimeter like a comma, semi-colon, colon, or forward slash", False)
End Sub
Protected Overrides Sub RegisterOutputParams(ByVal pManager As Grasshopper.Kernel.GH_Component.GH_OutputParamManager)
pManager.Register_StringParam("Tokenized Output", "O", "Tokenized Output")
End Sub
Protected Overrides Sub SolveInstance(ByVal DA As Grasshopper.Kernel.IGH_DataAccess)
Dim myString As String
DA.GetData(0, myString)
myString = myString.Replace(",", "|")
myString = myString.Replace(":", "|")
myString = myString.Replace(";", "|")
myString = myString.Replace("/", "|")
myString = myString.Replace(")(", "|")
myString = myString.Replace("(", String.Empty)
myString = myString.Replace(")", String.Empty)
Dim parts As String() = myString.Split("|"c)
DA.SetData(0, parts)
End Sub
End Class
This is the custom VB code I created inside Grasshopper:
Private Sub RunScript(ByVal myString As String, ByRef A As Object)
myString = myString.Replace(",", "|")
myString = myString.Replace(":", "|")
myString = myString.Replace(";", "|")
myString = myString.Replace("/", "|")
myString = myString.Replace(")(", "|")
myString = myString.Replace("(", String.Empty)
myString = myString.Replace(")", String.Empty)
Dim parts As String() = myString.Split("|"c)
A = parts
End Sub
'
'
End Class
Well, knowing nothing about Grasshopper, I'm just going to have to guess...
System.String [] is what .NET would print if you called ToString() on a string array. So, I'm gonna guess that you've given Grasshopper an array where it wants a single string.
So, with a little further guessing, how 'bout we try:
Dim parts As String() = myString.Split("|"c)
For I = 0 to parts.Length -1
DA.SetData(I, parts[I])
Well, I tried the code snippet you suggested... but it didn't quite work. I think the problem in the original code is that I'm trying to send a list of values (ie. parts) to a single output node. So, when I use DA.SetData(0,parts) I'm writing a list of values to the first output node of my compiled component. However, I think the problem is that the component doesn't know that parts is a list. In the example I gave before, if my incoming string is "123,456" then my result split list should have two values (123 and 456). I don't think I have declared parts to be a list. Do you have any ideas on how to do this? Again, if you click on the link in the original email (while using Internet Explorer... I'm not sure why Firefox isn't opening it) you should see a screenshot of the setup in the Grasshopper plugin which should help give you an idea of what's going on. Thanks again for your help.

.split removes tabs/spaces in string?

i am trying to split a string up into separate lines with the following code, but for some reason it is also removing the spaces in the string.
Dim calculationText As String
calculationText = File.ReadAllText(fileName)
Dim fields() As String
fields = calculationText.Split(vbCrLf)
when i am in debugger mode, i look at fields, and every element has a line of the string but all the spaces and tabs are removed.
any reason for this?
If you are reading from a file, can you use:
Sub Main()
Dim fields As New List(Of String)
' read file into list
Using sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(filename)
Try
Do While sr.Peek() >= 0
fields.Add(sr.ReadLine())
Loop
Finally
If sr IsNot Nothing Then sr.Close()
End Try
End Using
' check results
For Each line As String In fields
Console.WriteLine(line)
Next
End Sub
How 'bout:
Dim fields() As String = File.ReadAllLines(fileName)
As for why string.Split() is doing weird things...
vbCrLf is a string, and there's not an overload for string.split that accepts a single string parameter. If he were to turn on Option Explicit it wouldn't even compile, but since it's off, vbCrLf can be interpreted as an array of characters. And in this code, that's exactly what happens:
Sub Main()
Dim z As String = "The quick brown" & vbCrLf & " fox jumps over the lazy dogs."
Dim a() As String = z.Split(vbCrLf)
For Each c As String In a
Console.WriteLine(c)
Next
Console.ReadKey(True)
End Sub
You'll see two line breaks between the 1st and 2nd parts of that string. Something else is stripping out the spaces. Can you share the larger code block?
Gotta say I've never seen it do that, and I've used String.Split extensively. Are they really really gone, or is it a trick of the debugger?
There's not actually any .Split method that takes one string as the parameter, so the VB compiler would be doing "things" behind the scenes to pick a different overload. To try and force the correct overload, you could try calculationText.Split(vbCrLf.ToCharArray()). I doubt it will help, but you never know :-)

VB.NET missing isNull()?

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)