Search code examples
vb.netstringcompare

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

Solution

  • 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