Recipe 2.2 Determining Whether a Character Is Within a Specified Range

Problem

You need to determine whether a character in a char data type is within a range, such as between 1 and 5 or between A and M .

Solution

Use the built-in comparison support for the char data type. The following code shows how to use the built-in comparison support:

 public static bool IsInRange(char testChar, char startOfRange, char endOfRange) {     if (testChar >= startOfRange && testChar <= endOfRange)     {         // testChar is within the range         return (true);     }     else     {         // testChar is NOT within the range          return (false);     } } 

There is only one problem with that code. If the startOfRange and endOfRange characters have different cases, the result may not be what you expect. By adding the following code, which makes all characters uppercase, to the beginning of the method in Recipe 2.7, we can solve this problem:

 testChar = char.ToUpper(testChar); startOfRange = char.ToUpper(startOfRange); endOfRange = char.ToUpper(endOfRange); 

Discussion

The IsInRange method accepts three parameters. The first is the testChar character that you need to check on, to test if it falls between the last two parameters on this method. The last two parameters are the starting and ending characters, respectively, of a range of characters. The testChar parameter must be between startOfRange and endOfRange or equal to one of theses parameters for this method to return true ; otherwise , false is returned.

The IsInRange method can be called in the following manner:

 bool inRange = IsInRange('c', 'a', 'g'); bool inRange = IsInRange('c', 'a', 'b'); bool inRange = IsInRange((char)32, 'a', 'g'); 

The first call to this method returns true , since c is between a and g . The second method returns false , since c is not between a and b . The third method indicates how an integer value representative of a character would be passed to this method.

Note that this method tests whether the testChar value is inclusive between the range of characters startOfRange and endOfRange . If you wish to determine only whether testChar is between this range exclusive of the startOfRange and endOfRange character values, you should modify the if statement, as follows :

 if (testChar > startOfRange && testChar < endOfRange) 


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