Char.IsDigit
This C# method checks character values. It determines if a character in the string is a digit character—meaning it is part of an Arabic number—in the range 0-9.
IsDigit
is useful in parsing, scanning or sorting algorithms. It simply tests the range of the char
value. And this logic can be extracted from IsDigit
.
Consider the string
"abc123." The char.IsDigit
method should return false 3 times, and then true 3 times, in a string
loop.
a -> false b -> false c -> false 1 -> true 2 -> true 3 -> true
IsDigit()
is a static
method on the System.Char
struct
, which is aliased to the char
keyword. It returns true if the character is a digit character.
Main
entry point and an input string
. The string
contains lowercase letters, punctuation, and digits.IsDigit
returns True only for the digits. It accurately detects digit chars.using System; class Program { static void Main() { string test = "Abc,123"; foreach (char value in test) { bool digit = char.IsDigit(value); Console.Write(value); Console.Write(' '); Console.WriteLine(digit); } } /// <summary> /// Returns whether the char is a digit char. /// Taken from inside the char.IsDigit method. /// </summary> public static bool IsCharDigit(char c) { return ((c >= '0') && (c <= '9')); } }A False b False c False , False 1 True 2 True 3 True
The C# char.IsDigit
method tests for digits between 0 and 9. You can extract the character-testing logic for more predictable behavior and slightly better performance.