
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Determining the Kind of Character a char Contains
|
35
Solution
To determine the value of a char, use the built-in static methods on the System.Char
structure shown here:
Discussion
The following examples demonstrate how to use the methods shown in the Solution
section in a function to return the kind of a character. First, create an enumeration to
define the various types of characters:
public enum CharKind
{
Letter,
Number,
Punctuation,
Unknown
}
Next, create a method that contains the logic to determine the type of a character
and to return a
CharKind enumeration value indicating that type:
public static CharKind GetCharKind(char theChar)
{
if (Char.IsLetter(theChar))
{
return CharKind.Letter;
}
else if (Char.IsNumber(theChar))
{
return CharKind.Number;
}
else if (Char.IsPunctuation(theChar))
{
return CharKind.Punctuation;
}
else
{
return CharKind.Unknown;
}
}
If, however, a character in a string needs to be evaluated, use the overloaded static
methods on the
char structure. The following code modifies the GetCharKind method
to accept a
string variable and a character position in that string. The character posi-
tion determines which character in the string is evaluated.
Char.IsControl Char.IsDigit
Char.IsLetter Char.IsNumber
Char.IsPunctuation Char.IsSeparator
Char.IsSurrogate Char.IsSymbol ...