
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
38
|
Chapter 2: Strings and Characters
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 charac-
ters have different cases, the result may not be what you expect. The following code,
which makes a case-insensitive comparison, can be used to solve this problem:
public static bool IsInRangeCaseInsensitive(char testChar,
char startOfRange, char endOfRange)
{
testChar = char.ToUpper(testChar);
startOfRange = char.ToUpper(startOfRange);
endOfRange = char.ToUpper(endOfRange);
if (testChar >= startOfRange && testChar <= endOfRange)
{
// testChar is within the range.
return (true);
}
else
{
// testChar is NOT within the range.
return (false);
}
}
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 ...