Recipe 5.8. Comparing Strings with Case Sensitivity


You need to compare two strings, taking into account their case.


Use the shared Compare() method provided by the String object to compare two strings:

 Select Case String.Compare(content1, content2, False)    Case Is < 0       MsgBox("Content1 comes before Content2.")    Case Is > 0       MsgBox("Content1 comes after Content2.")    Case Is = 0       MsgBox("Content1 and Content2 are the same.") End Select 

Setting the third parameter of the Compare() method to False instructs the method to perform a case-sensitive comparison.


Consider the results shown in Figure 5-6, which indicate that "apples" is less than "Apples". The ASCII values for the lowercase character "a" and the uppercase character "A" are 97 and 65, respectively, which normally puts the uppercase version first. But the String.Compare() method compares text using culture-defined sorting rules, and by default, English words beginning with lowercase letters are considered "less than" the same words beginning with uppercase letters.

Figure 5-6. Culture-defined rules apply to case-sensitive string comparisons

You can change the comparison rules in several ways to match what you want to accomplish. See the Visual Studio online help for the CompareOptions property for more information on how to make these changes.

See Also

Recipe 5.9 discusses related comparisons.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: