Skip to content

[API Proposal]: char helpers for common ASCII categories #68868

@stephentoub

Description

@stephentoub

Background and motivation

We have a bunch of IsHex/IsHexChar/IsHexDigit helpers all around our libraries, as well as IsAsciiLetter/IsAsciiLetterOrDigit and such variants. We should expose these simple helpers implemented efficiently in a place all code can use rather than duplicating them into a bunch of libraries. We already have many Is* methods on char, like IsAscii, IsLetter, IsDigit, and so on; we can augment those with the additional methods.

API Proposal

public struct Char
{
+    public static bool IsAsciiDigit(char c); // true iff the char is 0-9
+    public static bool IsAsciiLetter(char c); // true iff the char is A-Z, a-z
+    public static bool IsAsciiLetterLower(char c); // true iff the char is a-z
+    public static bool IsAsciiLetterUpper(char c); // true iff the char is A-Z
+    public static bool IsAsciiLetterOrDigit(char c); // true iff the char is A-Z, a-z, 0-9

+    public static bool IsHexDigit(char c); // true iff the char is 0-9, A-F, a-f
+    public static bool IsHexDigitUpper(char c); // true iff the char is 0-9, A-F
+    public static bool IsHexDigitLower(char c); // true iff the char is 0-9, a-f

+    public static bool IsInRange(char c, char minInclusive, char maxInclusive); // true iff the char is >= minInclusive && <= maxInclusive
}

API Usage

if (char.IsAsciiLetterOrDigit(c))
{
    writer.Write(c);
}
else
{
    writer.Write($@"\u{(int)c:X4}");
}

Alternative Designs

We might also want to expose a helper for getting the value of a hex digit, e.g.

public static int GetHexDigitValue(char c); // return 0-15 for 0-9/A-F, and some sentinel otherwise (e.g. -1)

Risks

No response

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions