Hopefully this should be an easy question. In java i think it\'s compareTo()
.
How do I compare 2 string variables to determine if they are the same?
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
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
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 think this String.Equals is what you need.
Dim aaa = "12/31"
Dim a = String.Equals(aaa, "06/30")
a will return false.
I would suggest using the String.Compare method. Using that method you can also control whether to 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
If String.Compare(string1,string2,True) Then
'perform operation
EndIf