1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

String Comparison in VB.Net

Discussion in 'Visual Basic [VB]' started by pradeep, Mar 27, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Working with strings is a very important functionality in most applications. Your ability to effectively use the existing .NET functionality is vital for building solid applications.

    String.Compare method

    VB.NET's String.Compare method is handy when you need to compare two string variables. The parameters that you should specify in the String.Compare method are the first string that you need to compare, the string to which it will be compared, and the boolean value to determine whether case should be considered in the comparison. To ignore case, specify True; for the check to include the case, specify False. The returning value can be 1 if the ASCII value of the first string is higher; it can be -1 if the ASCII value of the second string is higher; and it can be 0 if both strings have the same value.

    Example

    Here's an example that demonstrates how the String.Compare method works. Add the following code to your module:
    Code:
      Private Sub CompareStrings()
      
          Dim str1, str2 As String
          str1 = "go4expert"
          str2 = "GO4expert"
      
          MessageBox.Show(String.Compare(str1, str2, False))
          MessageBox.Show(String.Compare(str1, str2, True))
      
      End Sub
    The initial message box will display -1; the second message box will display 0.

    In the code, I define and set the values for two string variables: str1 and str2. Then I pass three arguments - str1, str2, and a boolean value, which determines whether the string comparison will ignore or take into account the case of the strings being compared - to the string object's Compare method. Since the sum of ASCII values of the str2 variable is higher, the returned value is -1. So when I specify True as a last parameter and direct VB to ignore case differences, two strings have the same value and 0 is returned.
     

Share This Page