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.
In this quick tip, I discuss string comparison, which takes
into account case variety in the strings when cases are compared and when cases are ignored.
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.
Here’s an example that demonstrates how the String.Compare method works. Add the following code to your
Private Sub CompareStrings()
Dim str1, str2 As String
str1 = "Abc"
str2 = "ABc"
MessageBox.Show(String.Compare(str1, str2, False))
MessageBox.Show(String.Compare(str1, str2, True))
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.
Miss a tip?
Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya’s column.
Advance your scripting skills to the next level with TechRepublic’s free Visual Basic newsletter, delivered each Friday. Automatically sign up today!