aspguy
aspguy

Reputation:

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

Upvotes: 24

Views: 148774

Answers (6)

Fredrik Mörk
Fredrik Mörk

Reputation: 158389

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

Upvotes: 25

Aman
Aman

Reputation: 163

I think this String.Equals is what you need.

Dim aaa = "12/31"
            Dim a = String.Equals(aaa, "06/30")

a will return false.

Upvotes: -1

illuminati_confirmed
illuminati_confirmed

Reputation: 11

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

Upvotes: -1

Sreenath Munireddy
Sreenath Munireddy

Reputation: 11

If String.Compare(string1,string2,True) Then

    'perform operation

EndIf

Upvotes: -2

Robert Harvey
Robert Harvey

Reputation: 180908

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

Upvotes: 13

Tim
Tim

Reputation: 1826

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

Upvotes: 17

Related Questions