- Introduction
- Creating and Using String Objects
- Formatting Strings
- Accessing Individual String Characters
- Analyzing Character Attributes
- Case-Insensitive String Comparison
- Working with Substrings
- Using Verbatim String Syntax
- Choosing Between Constant and Mutable Strings
- Optimizing StringBuilder Performance
- Understanding Basic Regular Expression Syntax
- Validating User Input with Regular Expressions
- Replacing Substrings Using Regular Expressions
- Building a Regular Expression Library
3.5. Case-Insensitive String Comparison
You want to perform case-insensitive string comparison on two strings.
Technique
Use the overloaded Compare method in the System.String class which accepts a Boolean value, ignoreCase, as the last parameter. This parameter specifies whether the comparison should be case insensitive (true) or case sensitive (false). To compare single characters, convert them to uppercase or lowercase, using ToUpper or ToLower, and then perform the comparison.
Comments
Validating user input requires a lot of forethought into the possible values a user can enter. Making sure you cover the range of possible values can be a daunting task, and you might ultimately run into human-computer interaction issues by severely limiting what a user can enter. Case-sensitivity issues increase the possible range of values, leading to greater security with respect to such things as passwords, but this security is usually at the expense of a user's frustration when she forgets whether a character is capitalized. As with many other programming problems, you must weigh the pros and cons.
To perform a case-insensitive comparison, you can use one of the many overloaded Compare methods within the System.String class. The methods that allow you to ignore case issues use a Boolean value as the last parameter in the method. This parameter is named ignoreCase, and when you set it to true, you make a case-insensitive comparison, as demonstrated in Listing 3.6.
Listing 3.6 Performing a Case-Insensitive String Comparison
using System; namespace _5_CaseComparison { class Class1 { [STAThread] static void Main(string[] args) { string str1 = "This Is A String."; string str2 = "This is a string."; Console.WriteLine( "Case sensitive comparison of" + " str1 and str2 = {0}", String.Compare( str1, str2 )); Console.WriteLine( "Case insensitive comparison of" + " str1 and str2 = {0}", String.Compare( str1, str2, true )); } } }