0

How can I find which characters in a char[] are numbers?

char[] example = { '2', 'a', '4', 'f', 'u', 'i', '6' };

if(example[3] == ???) 
{
  Console.WriteLine(example[3].toString());
}
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
jonathanh8686
  • 78
  • 1
  • 6
  • English, Chinese, Indic, Arabic, Programmer? Always thought that 'a' and 'f' were perfectly good numbers, that's how I learned to program :) – Hans Passant Apr 01 '14 at 22:03

4 Answers4

3

char.IsDigit

So:

if (Char.IsDigit(example[3]))
{
   Console.WriteLine(...);
}

If you want all the chars:

IEnumerable<char> digitList = example.Where(c => Char.IsDigit(c));
//or
char[] digitArray = example.Where(c => Char.IsDigit(c)).ToArray();

Use Char.IsNumber if you want all the extra "numbers" in Unicode, specifically:

Numbers include characters such as fractions, subscripts, superscripts, Roman numerals, currency numerators, encircled numbers, and script-specific digits.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
2

Quite simply there is a method Char.IsNumber()

with which you can test:

char[] example = { '2', 'a', '4', 'f', 'u', 'i', '6' };

if(Char.IsNumber(example[3]))

{

  Console.WriteLine(example[3].toString());

}
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Saverio Terracciano
  • 3,885
  • 1
  • 30
  • 42
  • 2
    [The difference between Char.IsDigit() and Char.IsNumber()](http://stackoverflow.com/questions/228532/difference-between-char-isdigit-and-char-isnumber-in-c-sharp) – Erik Philips Apr 01 '14 at 21:57
1

If you want to get all the numbers:

var numbers = example.Where(char.IsDigit);

If you want to check whether specific char is number or not:

if(char.IsDigit(example[3]))
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0
static void Main(string[] args)
        {

            char[] example = { '2', 'a', '4', 'f', 'u', 'i', '6' };

            if (char.IsDigit(example[3]))

            {

                Console.WriteLine(example[3]);

            }

        }
BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47