2.1. Determining the Kind of Character a Char Contains
Problem
You have a variable of type char and wish to determine the kind of character it contains—a letter, digit, number, punctuation character, control character, separator character, symbol, whitespace, or surrogate character (i.e., Unicode characters with a value greater than 64K). Similarly, you have a string variable and want to determine the kind of character in one or more positions within this string.
Solution
To determine the value of a char, use the built-in static methods on the System.Char structure shown here:
Char.IsControl Char.IsDigit Char.IsLetter Char.IsNumber Char.IsPunctuation Char.IsSeparator Char.IsSurrogate Char.IsSymbol Char.IsWhitespace
Discussion
The following examples demonstrate how to use the methods shown in the Solution section in an extension method to return the kind of a character. First, create an enumeration to define the various types of characters:
public enum CharKind
{
Digit,
Letter,
Number,
Punctuation,
Unknown
}Next, create the extension method that contains the logic to determine the kind of a character and to return a CharKind enumeration value indicating that type:
static class CharStrExtMethods
{
public static CharKind GetCharKind(this 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;
}
}
}The GetCharKind ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access