How to check if a character is a digit in C#
Overview
A character can be an alphabet, symbol, etc. In other words, a character can be alphanumeric. In C#, we can use the IsDigit() method to check if a character is numeric or a digit.
The IsDigit() method can be used on a single character or on a string. In the case of a string, we have to specify the index position of the character in the string.
IsDigit() returns true if the character is a decimal digit; otherwise, it returns false.
Syntax
// on character
IsDigit(Char)
// on a string
IsDigit(String, int32)
Parameters
-
Char: The character we want to check. -
String: The string that we want to check to see if any character at index positionint32is a digit. -
int32: The index position of the character in a string we want to check.
Code example
In the example below, we create some strings and characters and see if certain characters are decimal digits or not.
// use systemusing System;// create classclass DigitChecker{static void Main(){// create characterschar char1 = '5';char char2 = 'p';// create stringsstring str1 = "1234";string str2 = "hi";// check charactersbool a = Char.IsDigit(char1);bool b = Char.IsDigit(char2);bool c = Char.IsDigit(str1, 2); // position 3bool d = Char.IsDigit(str2, 0); // position 1// print out returned valuesSystem.Console.WriteLine(a);System.Console.WriteLine(b);System.Console.WriteLine(c);System.Console.WriteLine(d);}}
Explanation
In the code above, line 17 and line 19 return true because the value of char1, which is 5, is actually a numeric value/digit. str1 has 3 at position 3, which is also a number.
The other lines return false because the values are not decimal digits.