Recipe 2.7 Controlling Case Sensitivity when Comparing Two Strings

Recipe 2.7 Controlling Case Sensitivity when Comparing Two Strings

Problem

You need to compare the contents of two strings for equality. In addition, the case sensitivity of the comparison needs to be controlled.

Solution

Use the Compare static method on the string class to compare the two strings. Whether the comparison is case-insensitive is determined by the third parameter of one of its overloads. For example:

 string lowerCase = "abc"; string upperCase = "AbC"; int caseSensitiveResult = string.Compare(lowerCase, upperCase, false); int caseInsensitiveResult = string.Compare(lowerCase, upperCase, true); 

The caseSensitiveResult value is -1 (indicating that lowerCase is "less than" upperCase ) and the caseInsensitiveResult is zero (indicating that lowerCase "equals" upperCase ).

Discussion

Using the static string.Compare method allows us the freedom to choose whether to take into account the case of the strings when comparing them. This method returns an integer indicating the lexical relationship between the two strings. A zero means that the two strings are equal, a negative number means that the first string is less than the second string, and a positive number indicates that the first string is greater than the second string.

By setting the last parameter of this method (the IgnoreCase parameter) to true or false , we can determine whether the Compare method takes into account the case of both strings when comparing. Setting this parameter to true forces a case-insensitive comparison and setting this parameter to false forces a case-sensitive comparison. In the case of the overloaded version of the method with no IgnoreCase parameter, comparisons are always case-sensitive.

See Also

See the "String.Compare Method" topic in the MSDN documentation.



C# Cookbook
C# 3.0 Cookbook
ISBN: 059651610X
EAN: 2147483647
Year: 2003
Pages: 315

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net