Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# char.IsLetterOrDigit Method

This C# article shows the char.IsLetterOrDigit method. It tests the performance of this method.

Char.IsLetterOrDigit. The char.IsLetterOrDigit method tests a char.

It determines if the char is a letter or digit. We run this method through a simple test to demonstrate its use. We present some example input and output.

Example. Let's get started with a simple Console program that uses an input string containing various characters. We loop over these characters with the foreach-loop construct, and pass each character to the char.IsLetterOrDigit method.

Then: We display a character to indicate whether the input character was considered a letter or digit.

C# program that uses char.IsLetterOrDigit

using System;

class Program
    static void Main()
	string input = "The Developer Blog 867-5309?!";

	foreach (char letter in input)
	    bool isLetterOrDigit = char.IsLetterOrDigit(letter);
	    if (isLetterOrDigit)
		Console.Write(' ');


The Developer Blog 867-5309?!
^^^ ^^^ ^^^^^ ^^^ ^^^^

The letters and digits, but not the spaces, hyphen and other punctuation received a true value from IsLetterOrDigit. The method's output is equivalent to the expression (char.IsLetter(letter) || char.IsDigit(letter)).

True, False

Performance. The performance of character-testing methods is often improved with a lookup table. This reduces the cost of the method to a single array access. Most often, though, char.IsLetterOrDigit is not something that needs to be optimized.

Frequency analysis can yield improvement. If most of your characters are digits, testing first to see if the character is a digit would be fastest. In my limited testing, char.IsLetterOrDigit does not test for digits first.

So: Its performance on a digit is worse than (char.IsDigit(letter) || char.IsLetter(letter)).

Info: The char.IsLetterOrDigit method seemed to take somewhat less than 3 nanoseconds on my computer.

Summary. We looked at the behavior of the char.IsLetterOrDigit method from the .NET Framework and noted its performance. Largely a convenience method over using char.IsLetter and char.IsDigit, this method can yield a simplification.