Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Visual Basic [VB] (http://www.go4expert.com/articles/visual-basic-tutorials/)
-   -   String Comparison in VB.Net (http://www.go4expert.com/articles/string-comparison-vbnet-t3642/)

pradeep 27Mar2007 17:36

String Comparison in VB.Net
 
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: VB

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.


All times are GMT +5.5. The time now is 11:23.