Comparing strings in a loop using Is Operator - vb.net

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

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 "").

How to remove a character from at string at certain position from the end?

I have a string, for example:
Dim str as string = xxxxxxxxxxxxxxxxxxxx£xxx£xxxx**£**xxxxxxxxxx
I want to remove £ surrounded from * which is always at a certain position (11th for instance) from the end. The whole string is a long one, always change in size and cannot be counted from the start. I cannot use Replace as well, there may be same characters at other positions that I do not wish to remove.
Solution:
Dim rst As String = str.Remove(str.Length - 11, 1)
Edit: Whoops, I dunno what I was thinking on that first part.
The correct version of the first part would be:
str = str.Substring(0, str.Len -13) + str.Substring(str.Len-11);
There also may be an overload for the String.Delete function that allows you to use a negative number to represent the number of characters from the end of the string -- I know that the C# equivalent does.
If its always going to be the 11th character from the end you can do this...
Dim strTargetString As String = "xxxYxxxxxxxxxx"
Dim strTargetString2 As String = "xxxxxxxYxxxxxxxxxx"
Dim strResult As String = Mid(strTargetString, 1, (Len(strTargetString) - 11)) & Microsoft.VisualBasic.Right(strTargetString, 10)
Dim strResult2 As String = Mid(strTargetString2, 1, (Len(strTargetString2) - 11)) & Microsoft.VisualBasic.Right(strTargetString, 10)
Note that String.SubString is a more modern approach than Mid, but I use it out of preference and example.
This is fairly straightforward with a regular expression replacement operation using look-ahead:
Dim str as String = "xxxxxxxxxxxxxxxxxxxx£xxx£xxxx£xxxxxxxxxx"
Dim str2 as String = Regex.Replace(str, "£(?=.{10}$)", String.Empty)
This will target a single character followed by any ten characters then the end of the string and replace it with the String.Empty value (or just "" if you'd prefer).

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.

Create a string and append text to it

Funny, I had a textbox and I could append strings to it.
But now I create a string like this:
Dim str As String = New String("")
And I want to append to it other strings. But there is no function for doing so. What am I doing wrong?
Concatenate with & operator
Dim str as String 'no need to create a string instance
str = "Hello " & "World"
You can concate with the + operator as well but you can get yourself into trouble when trying to concatenate numbers.
Concatenate with String.Concat()
str = String.Concat("Hello ", "World")
Useful when concatenating array of strings
StringBuilder.Append()
When concatenating large amounts of strings use StringBuilder, it will result in much better performance.
Dim sb as new System.Text.StringBuilder()
str = sb.Append("Hello").Append(" ").Append("World").ToString()
Strings in .NET are immutable, resulting in a new String object being instantiated for every concatenation as well a garbage collection thereof.
Another way to do this is to add the new characters to the string as follows:
Dim str As String
str = ""
To append text to your string this way:
str = str & "and this is more text"
Use the string concatenation operator:
Dim str As String = New String("") & "some other string"
Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.
This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.
See "How to: Concatenate Multiple Strings" for more information on both methods.

Comparing strings in VB.NET

Hopefully this should be an easy question. In Java I think it's compareTo().
How do I compare two string variables to determine if they are the same?
ie:
If (string1 = string2 And string3 = string4) Then
'perform operation
Else
'perform another operation
End If
I would suggest using the String.Compare method. Using that method you can also control whether to have it perform case-sensitive comparisons or not.
Sample:
Dim str1 As String = "String one"
Dim str2 As String = str1
Dim str3 As String = "String three"
Dim str4 As String = str3
If String.Compare(str1, str2) = 0 And String.Compare(str3, str4) = 0 Then
MessageBox.Show("str1 = str2 And str3 = str4")
Else
MessageBox.Show("Else")
End If
Edit: If you want to perform a case-insensitive search you can use the StringComparison parameter:
If String.Compare(str1, str2, StringComparison.InvariantCultureIgnoreCase) = 0 And String.Compare(str3, str4, StringComparison.InvariantCultureIgnoreCase) = 0 Then
In vb.net you can actually compare strings with =. Even though String is a reference type, in vb.net = on String has been redefined to do a case-sensitive comparison of contents of the two strings.
You can test this with the following code. Note that I have taken one of the values from user input to ensure that the compiler cannot use the same reference for the two variables like the Java compiler would if variables were defined from the same string Literal. Run the program, type "This" and press <Enter>.
Sub Main()
Dim a As String = New String("This")
Dim b As String
b = Console.ReadLine()
If a = b Then
Console.WriteLine("They are equal")
Else
Console.WriteLine("Not equal")
End If
Console.ReadLine()
End Sub
Dim MyString As String = "Hello World"
Dim YourString As String = "Hello World"
Console.WriteLine(String.Equals(MyString, YourString))
returns a bool True. This comparison is case-sensitive.
So in your example,
if String.Equals(string1, string2) and String.Equals(string3, string4) then
' do something
else
' do something else
end if
I know this has been answered, but in VB.net above 2013 (the lowest I've personally used) you can just compare strings with an = operator. This is the easiest way.
So basically:
If string1 = string2 Then
'do a thing
End If
I think this String.Equals is what you need.
Dim aaa = "12/31"
Dim a = String.Equals(aaa, "06/30")
a will return false.
If String.Compare(string1,string2,True) Then
'perform operation
EndIf