Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
comm
communitycreator

How to check if a character is a digit in C#

Theodore Kelechukwu Onyejiaku

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 position int32 is 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 system
using System;
// create class
class DigitChecker
{
    static void Main()
    {
      // create characters
      char char1 = '5';
      char char2 = 'p';

      // create strings
      string str1 = "1234";
      string str2 = "hi";

      // check characters
      bool a = Char.IsDigit(char1);
      bool b = Char.IsDigit(char2);
      bool c = Char.IsDigit(str1, 2);   // position 3
      bool d = Char.IsDigit(str2, 0);    // position 1

      // print out returned values
      System.Console.WriteLine(a);
      System.Console.WriteLine(b);
      System.Console.WriteLine(c);
      System.Console.WriteLine(d);
    }
}
Using the "isDigit" method

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.

RELATED TAGS

c#
comm
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring