Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
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 ...
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.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
C# Cookbook

C# Cookbook

Joe Mayo
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata